So, I have some string Array:
Column1 Column3
and I have class with fields
class A
{
object Column1;
object Column2;
object Column3;
object Column4;
object Column5;
}
Now I have a list of A objects
List<A> ListOfA = new List<A>();
That list has N elements.
Now, How I can cast it to some object from that array? And have List<NewAnonymous>
I want to have list of new { Column1 = '', Column3=''}
but I never know what columns will be in that array.
Is this even possible? If yes, where i can look for it. I have some code ofcourse but it I think it wont help so i just tried to explain what I want to say
Based on the comments on the question I would suggest:
foreach (A a in listOfA)
{
var t = typeof(A);
List<object> list = new List<object>();
foreach (var prop in t.GetProperties())
{
list.Add(prop.GetValue(a));
}
newListOfA.Add(list);
}
Edit: If you prefer non query based LINQ here is an extension on EarthEngine's LINQ
t = typeof(A)
listOfA.SelectMany(o=>t.GetProperties().Select(i=>i.GetValue(o))
Same answer as Murdock's, but with pure LINQ
from a in listOfA
let t = typeof(A)
from prop in t.GetProperties()
select prop.GetValue(a)
I'm going to buck the current trend and say you could do so via reflection, but you shouldn't.
Why? Because now you have an anonymous type that you don't "know" the properties of. How will you use that downstream? More reflection?
If you have an unknown number of fields it would be best to deal with them in an indexed manner (List or Dictionary) as opposed to that sinkhole of reflection.
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.