sgtz
sgtz

Reputation: 9019

LINQ list property to array?

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.

Upvotes: 15

Views: 16071

Answers (2)

Bobby Richard
Bobby Richard

Reputation: 648

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

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

Upvotes: 9

JConstantine
JConstantine

Reputation: 3931

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

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

Upvotes: 29

Related Questions