4thSpace
4thSpace

Reputation: 44312

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?

Upvotes: 0

Views: 195

Answers (3)

Gilad Green
Gilad Green

Reputation: 37299

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);
}

Upvotes: 4

Sehnsucht
Sehnsucht

Reputation: 5049

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

Upvotes: 0

kemiller2002
kemiller2002

Reputation: 115420

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

Upvotes: 3

Related Questions