简体   繁体   中英

Linq group by using reflection

I have data table "Car" which have 3 cols (owner, carType, colour). My question is how can i make the grouping portion more dynamic by using reflection. my idea is add the grouping col in to array, then use the reflection on the query grouping part. however i was struck at the reflection..

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM