开发者

LINQ list property to array?

开发者 https://www.devze.com 2023-04-01 07:06 出处:网络
What\'s the best way to do this where PROPNAME could be any property of type T?Build it up with reflection, or is there a good LINQ way of doing this?

What's the best way to do this where PROPNAME could be any property of type T? Build it up with reflection, or is there a good LINQ way of doing this?

T[] vals = people.Select(x => x.PROPNAME).ToArray<T>();

this is the best I've got so far:

    public T[] ConvertListCol<TFrom,T>(IEnumerable<TFrom> list, string col)
    {
 开发者_如何学编程       var typ = typeof (TFrom);
        var props = typ.GetProperties();
        var prop = (from p in props where p.Name == col select p).FirstOrDefault();
        var ret = from o in list select prop.GetValue(o, null);
        return ret.ToArray<T>();
    }

Got an error in the return... but getting closer. It's okay, but a little messier than I'd hoped.


Using a non-explicit var type, it will automatically generate the type for you

var names = people.Select(x => x.PROPNAME).ToArray();


The type will be inferred if you use the var keyword:

var names = people.Select(x => x.PROPNAME).ToArray();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号