简体   繁体   中英

How to get value of specific property from list?

I have the following class:

public class ClassA
{
   public string Property1 { get; set; }
   public string Property2 { get; set; }
   public string Property3 { get; set; }
}

There are instances of the class in a List<ClassA> . How do I get a List<string> of values for Property2 from all classes?

You can use Linq.Select to do so:

List<ClassA> list = new List<ClassA>
{
    new ClassA { Property2 = "value 1"},
    new ClassA { Property2 = "value 2"},
};

//This is method syntax
var result = list.Select(item => item.Property2).ToList();

//This is query syntax
var result = (from item in list
             select item.Property2).ToList();

Keep not that the ToList() are not a must and are here just for ease in using this code example

The Select basically boils down to something similar to:

List<string> response = new List<string>();
foreach(var item in list)
{
    response.Add(item.Property2);
}

You can use Select

var properties = listOfA.Select(x=>x.Property2);

or through the query syntax :

    var list = new List<ClassA>();

    var properties = from item in list
                     select item.Property2

To change from the Select(...).ToList() "pattern" you can also use the existing method inside List<T> which do the job, namely ConvertAll using nearly the same exact code.

// source is your List<ClassA>
var result = source.ConvertAll(item => item.Property2);
// result is already a List<string> so no need for extra code

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM