Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ list property to array?

Tags:

arrays

c#

linq

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.

like image 535
sgtz Avatar asked Aug 31 '11 17:08

sgtz


1 Answers

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

var names = people.Select(x => x.PROPNAME).ToArray();
like image 97
JConstantine Avatar answered Oct 22 '22 00:10

JConstantine