1

我有数据表“汽车”,它有 3 个列(所有者、汽车类型、颜色)。我的问题是如何通过使用反射使分组部分更加动态。我的想法是将分组 col 添加到数组中,然后在查询分组部分使用反射。但是我对反射感到震惊..

var gcols = new string[] { "owner", "carType" };                         
var reseult = dt.AsEnumerable()
                     .GroupBy(x => new
                     {
                         carType = x.Field<string>("carType"),
                         colour = x.Field<string>("colour")
                     })
                     .Select(x => new
                     {
                         CarType = x.Key.carType,
                         Colour = x.Key.colour,
                         count = x.Count()
                     })
                    .OrderBy(x => x.CarType).ToList();
4

1 回答 1

1

If you added this extension method to object:

    public static T Field<T>(this object source, string FieldName)
    {
        var type = source.GetType();
        var field = type.GetField(FieldName);
        return (T)field.GetValue(source);
    }

You'd be able to use the syntax you've posted in your code.

I've not added any safety checking here so it'll need cleaning up, but it'll get you going. Ideally you'd want to check that the type of field is the same as T and a few other checks.

于 2013-04-15T09:00:55.217 回答