好的,所以我有一个 POCO 类,它可能包含另一个 POCO 类作为数组。在某些情况下,当我获取数据时,我想创建一个列表列表,但不是作为一个级别,而是在同一级别上。我想我错过了一些非常简单的东西,所以我想我会在这里问。我一直在为 Lambda 尝试不同的语法,但数据就在那里,我永远无法让它出现在顶部附近。如果可能的话,我希望解决方案使用 lambdas,而不是使用老式的 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);
}
}