c#如何创建自定义对象的集合,而无需浏览每个字段 [英] c# How can I create a collection of custom objects without going through each field

查看:417
本文介绍了c#如何创建自定义对象的集合,而无需浏览每个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个名为 DataResponse 的类,它有超过40个公共字段。类 DataResponse 具有与我的数据库中的相同数量的字段和类型 DataRepoes (让我们假设)。

I have created a class called DataResponse that has more than 40 public fields. The class DataResponse has the same number of fields and type as what's in my database DataRepoes (let's assume that).

有一种方法可以在linq下面创建对象列表,并自动将字段分配给 DataResponse 从什么在DB?否则,我必须拼出每一个每个这40个字段,并在我新建DataResponse类时手动分配。感谢

Is there a way at all to do something like linq below where I create list of objects and automatically the fields are assigned to DataResponse from what's in the DB? Otherwise I have to spell out each and every those 40 fields and assign them manually when I new up DataResponse class. Thanks

List<Classes.DataResponse> res = (from rx in con.DataRepoes
  where iaccess.Contains(rx.STOREID)
  select new Classes.DataResponse).ToList<Classes.DataResponse>();


推荐答案

如果您不需要AutoMapper或不想使用第三方库,可以使用以下简化的自定义扩展方法:

If you don't need the flexibility provided by AutoMapper or don't want using a third party library, you can use the following simplified custom extension method:

public static class QueryableExtensions
{
    public static IQueryable<TResult> SelectTo<TResult>(this IQueryable source)
    {
        var sourceType = source.ElementType;
        var resultType = typeof(TResult);
        var parameter = Expression.Parameter(sourceType, "x");
        var bindings =
            from rm in resultType.GetProperties().Concat<MemberInfo>(resultType.GetFields())
            join sm in sourceType.GetProperties().Concat<MemberInfo>(sourceType.GetFields())
                on rm.Name equals sm.Name
            select Expression.Bind(rm, Expression.MakeMemberAccess(parameter, sm));
        var body = Expression.MemberInit(Expression.New(resultType), bindings);
        return source.Provider.CreateQuery<TResult>(Expression.Call(
            typeof(Queryable), "Select", new[] { sourceType, resultType },
            source.Expression, Expression.Quote(Expression.Lambda(body, parameter))));
    }
}

它将尝试选择所有属性/字段匹配按名称。

It will try to select all the properties/fields that match by name. Will fail if matched property/field types differ.

示例用法:

方法语法

var res = con.DataRepoes
    .Where(rx => iaccess.Contains(rx.STOREID))
    .SelectTo<Classes.DataResponse>()
    .ToList();

查询语法

var res =
    (from rx in con.DataRepoes
     where iaccess.Contains(rx.STOREID)
     select rx)
    .SelectTo<Classes.DataResponse>()
    .ToList();

这篇关于c#如何创建自定义对象的集合,而无需浏览每个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆