Get list of properties from List of objects
C#C# Problem Overview
Currently I use foreach
loop to return a list of object
properties.
class X
{
List<X> Z = GetXlist();
List<String> r = new List<String>();
foreach (var z in Z)
{
r.Add(z.A);
}
return r;
}
Is there a way that I can shorten this so that I don't have to write the foreach
loop?
C# Solutions
Solution 1 - C#
LINQ is the answer. You can use it to "project" from your object collection to another collection - in this case a collection of object property values.
List<string> properties = objectList.Select(o => o.StringProperty).ToList();
Solution 2 - C#
You could use LINQ:
List<X> Z = GetXlist();
List<String> r = Z.Select(z => z.A).ToList();
return r;
Or just,
return GetXlist().Select(z => z.A).ToList();
Find out more about LINQ. It is pretty useful.
Solution 3 - C#
List<string> properties = objectList.Select(o => o.StringProperty).ToList();
You Also Can Do By Private OverLoading
Method and Use That in LINQ Query.