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(),以实际执行查询,特别是当您要多次枚举列表时。