简体   繁体   English

如何从列表中获取特定属性的值?

[英]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> . List<ClassA>中有该类的实例。 How do I get a List<string> of values for Property2 from all classes? 如何从所有类中获取Property2的值的List<string>

You can use Linq.Select to do so: 您可以使用Linq.Select来这样做:

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 请记住, ToList()不是必须的,此处只是为了方便使用此代码示例

The Select basically boils down to something similar to: Select基本上归结为类似于以下内容:

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. 要从Select(...).ToList() “模式”中进行更改,您还可以使用List<T>内部执行此工作的现有方法,即ConvertAll使用几乎相同的精确代码。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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