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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1615362View Question on Stackoverflow
Solution 1 - C#Honza BrestanView Answer on Stackoverflow
Solution 2 - C#rae1View Answer on Stackoverflow
Solution 3 - C#AnshumanView Answer on Stackoverflow