使用lambda表达式从Linq中列表中的列表创建新的泛型列表?
好的,我有一个POCO类,它可能包含另一个POCO类作为数组。在某些情况下,当我获取数据时,我希望创建一个列表列表,但不是作为一个级别,而是所有列表都在同一级别上。我想我遗漏了一些非常简单的东西,所以我想在这里问一下。我一直在尝试Lambdas的不同语法,但是数据就在那里,我永远无法让它显示在顶部附近。如果可能的话,我希望解决方案是在lambdas中,而不是在做老式的foreach。我不确定您是否可以内联执行此操作,或者是否必须先声明一个集合,然后再添加到其中。我现在的位置:使用lambda表达式从Linq中列表中的列表创建新的泛型列表?,linq,c#-4.0,lambda,poco,Linq,C# 4.0,Lambda,Poco,好的,我有一个POCO类,它可能包含另一个POCO类作为数组。在某些情况下,当我获取数据时,我希望创建一个列表列表,但不是作为一个级别,而是所有列表都在同一级别上。我想我遗漏了一些非常简单的东西,所以我想在这里问一下。我一直在尝试Lambdas的不同语法,但是数据就在那里,我永远无法让它显示在顶部附近。如果可能的话,我希望解决方案是在lambdas中,而不是在做老式的foreach。我不确定您是否可以内联执行此操作,或者是否必须先声明一个集合,然后再添加到其中。我现在的位置: class Pro
class Program
{
public class lowerlevel
{
public string ChildName;
}
public class upperlevel
{
public string ItemName;
public lowerlevel[] ChildNames;
}
static void Main(string[] args)
{
// Create a list of a POCO object that has lists in it as well.
List<upperlevel> items = new List<upperlevel>
{
// declaration of top level item
new upperlevel
{
ItemName = "FirstItem",
// declaration of children
ChildNames = new lowerlevel[]
{new lowerlevel {ChildName = "Part1"}, new lowerlevel {ChildName = "Part2"}},
},
// declaration of top level item
new upperlevel
{
ItemName = "SecondItem",
// declaration of children
ChildNames = new lowerlevel[] { new lowerlevel { ChildName = "Part3" } }
}
};
var stuff = items.Select(l1 => l1.ChildNames.ToList().Select(l2 =>
new lowerlevel
{
ChildName = l2.ChildName
}))
.ToList();
// Arghh! I just want to make a new list with lambdas that is NOT nested a level down! This is NOT what I want but it is valid.
stuff.ForEach(n => n.ToList().ForEach(n2 => n2.ChildName));
// I want this but it does not work as I am not doing the expression right
// stuff.Foreach(n => n.ChildName);
}
}
类程序
{
公共级下层
{
公共字符串ChildName;
}
公共阶级上层
{
公共字符串ItemName;
公共低级别[]儿童姓名;
}
静态void Main(字符串[]参数)
{
//创建包含列表的POCO对象的列表。
列表项=新列表
{
//顶级项目的申报
新上层
{
ItemName=“FirstItem”,
//儿童宣言
ChildNames=新的lowerlevel[]
{new lowerlevel{ChildName=“Part1”},new lowerlevel{ChildName=“Part2”},
},
//顶级项目的申报
新上层
{
ItemName=“SecondItem”,
//儿童宣言
ChildNames=new lowerlevel[]{new lowerlevel{ChildName=“Part3”}
}
};
var stuff=items.Select(l1=>l1.ChildNames.ToList().Select(l2=>
新lowerlevel
{
ChildName=l2.ChildName
}))
.ToList();
//Arghh!我只想用lambdas创建一个新的列表,该列表没有向下嵌套一级!这不是我想要的,但它是有效的。
ForEach(n=>n.ToList().ForEach(n2=>n2.ChildName));
//我想要这个,但它不工作,因为我没有做正确的表达
//Foreach(n=>n.ChildName);
}
}
尝试使用SelectMany()
而不是。Select()
我认为SelectMany()就是您想要的。如果我将它放在我的示例中的“items”之后,似乎就是这样。谢谢
var stuff = items.SelectMany...