C# 如何将具有相同类型项目的列表列表合并为单个项目列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1191054/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 10:26:16  来源:igfitidea点击:

How to merge a list of lists with same type of items to a single list of items?

c#linqlambda

提问by David.Chu.ca

The question is confusing, but it is much more clear as described in the following codes:

这个问题令人困惑,但如以下代码所述,它更加清晰:

   List<List<T>> listOfList;
   // add three lists of List<T> to listOfList, for example
   /* listOfList = new {
        { 1, 2, 3}, // list 1 of 1, 3, and 3
        { 4, 5, 6}, // list 2
        { 7, 8, 9}  // list 3
        };
   */
   List<T> list = null;
   // how to merger all the items in listOfList to list?
   // { 1, 2, 3, 4, 5, 6, 7, 8, 9 } // one list
   // list = ???

Not sure if it possible by using C# LINQ or Lambda?

不确定是否可以使用 C# LINQ 或 Lambda?

Essentially, how can I concatenate or "flatten" a list of lists?

本质上,我如何连接或“展平”列表列表?

采纳答案by JaredPar

Use the SelectMany extension method

使用 SelectMany 扩展方法

list = listOfList.SelectMany(x => x).ToList();

回答by IRBMe

Do you mean this?

你是这个意思吗?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

结果是: 9 9 9 1 2 3 4 5 6

回答by Joe Chung

Here's the C# integrated syntax version:

这是 C# 集成语法版本:

var items =
    from list in listOfList
    from item in list
    select item;

回答by Arman McHitarian

For List<List<List<x>>>and so on, use

对于List<List<List<x>>>等等,使用

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

这已发布在评论中,但在我看来确实值得单独回复。