好的,所以我有一个POCO类可能包含另一个POCO类作为数组。在某些情况下,当我获取数据时,我想创建一个列表列表,但不是作为一个级别,而是在同一级别上。我想我错过了很简单的东西,所以我想我会在这里问。我一直在为Lambdas尝试不同的语法,但数据就在那里,我可以永远不会让它出现在顶部附近。如果可能的话,我希望解决方案是lambda,而不是做旧的foreach。我不确定你是否可以内联,或者你必须首先声明一个集合然后添加它。我在哪里:
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);
}
}
答案 0 :(得分:1)
尝试使用SelectMany()
而不是.Select()
var stuff = items.SelectMany...