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();
精彩评论