Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/linq/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从双层对象列表中选择某些对象特性的列表_C#_Linq - Fatal编程技术网

C# 从双层对象列表中选择某些对象特性的列表

C# 从双层对象列表中选择某些对象特性的列表,c#,linq,C#,Linq,我有一些对象的双层列表。我想根据一些条件得到一些属性值的列表 前 我有以下课程 public class Demo { public string Prop1 {get; set;} public string Prop2 {get; set;} } 我已经创建了上述类对象的双重列表 List<List<Demo>> lst = new List<List<Demo>>(); List<Demo> lstdemo1

我有一些对象的双层列表。我想根据一些条件得到一些属性值的列表

我有以下课程

public class Demo
{
    public string Prop1 {get; set;}
    public string Prop2 {get; set;}
}
我已经创建了上述类对象的双重列表

List<List<Demo>> lst = new List<List<Demo>>();

List<Demo> lstdemo1 = new List<Demo>
lstdemo1.Add(new Demo(){Prop1 = "1", Prop2="abc"});
lstdemo1.Add(new Demo(){Prop1 = "2", Prop2="pqr"});

List<Demo> lstdemo2 = new List<Demo>
lstdemo2.Add(new Demo(){Prop1 = "1", Prop2="mno"});
lstdemo2.Add(new Demo(){Prop1 = "2", Prop2="xyz"});

lst.Add(lstdemo1);
lst.Add(lstdemo2);
List lst=new List();
列表lstdemo1=新列表
添加(newdemo(){Prop1=“1”,Prop2=“abc”});
lstdemo1.Add(newdemo(){Prop1=“2”,Prop2=“pqr”});
列表lstdemo2=新列表
添加(newdemo(){Prop1=“1”,Prop2=“mno”});
添加(newdemo(){Prop1=“2”,Prop2=“xyz”});
第一次增补(第1次修订);
第1条增补(第2条);
现在我想得到一个有Prop2值的列表,它依赖于Prop1值 例如:我想得到Prop2的列表,其中Prop1等于“1”

我想要以下输出
列表
lst输出 其中包含

“abc”、“mno”

使用:

使用:


最简单的方法是使用LINQ的
SelectMany
来展平列表。使用查询语法中的两个
from
子句完成此操作:

var query = from x in lst
            from y in x
            where y.Prop1.Equals("1")
            select y.Prop2;
或者,在方法语法中调用
SelectMany

var query = lst.SelectMany(x => x.Where(y => y.Prop1.Equals("1"))
                                 .Select(y => y.Prop2));

最简单的方法是使用LINQ的
SelectMany
来展平列表。使用查询语法中的两个
from
子句完成此操作:

var query = from x in lst
            from y in x
            where y.Prop1.Equals("1")
            select y.Prop2;
或者,在方法语法中调用
SelectMany

var query = lst.SelectMany(x => x.Where(y => y.Prop1.Equals("1"))
                                 .Select(y => y.Prop2));

没问题。如果您是LINQ新手,请不要忘记对结果调用ToList(),以实际执行查询,特别是如果您要对列表进行多次枚举,这不是问题。如果您是LINQ新手,请不要忘记对结果调用ToList(),以实际执行查询,特别是当您要多次枚举列表时。