【问题标题】:Make a new generic list from a list within a list in Linq with lambda expressions?使用 lambda 表达式从 Linq 列表中的列表中创建一个新的通用列表?
【发布时间】:2013-05-10 17:55:56
【问题描述】:

好的,所以我有一个 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);

        }

    }

【问题讨论】:

  • 我认为 SelectMany() 是您正在寻找的。​​span>
  • 如果我将它放在我的示例中的“项目”之后,似乎就是这样。谢谢!

标签: linq c#-4.0 lambda poco


【解决方案1】:

尝试使用SelectMany() 而不是.Select()

var stuff = items.SelectMany...

【讨论】:

    猜你喜欢
    • 2015-01-24
    • 1970-01-01
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多