[C#] 동일한 유형의 항목이있는 목록 목록을 단일 항목 목록에 병합하는 방법은 무엇입니까?

이 질문은 혼란 스럽지만 다음 코드에서 설명하는 것처럼 훨씬 명확합니다.

   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 = ???

C # LINQ 또는 Lambda를 사용하여 가능한지 확실하지 않습니까?

기본적 으로 목록을 어떻게 연결하거나 ” 평평하게 ” 할 수 있습니까?



답변

SelectMany 확장 방법 사용

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


답변

C # 통합 구문 버전은 다음과 같습니다.

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


답변

당신은 이것을 의미합니까?

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);

결과 : 9 9 9 1 2 3 4 5 6


답변

의 경우 List<List<List<x>>>등, 사용에

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

이것은 의견에 게시되었지만 내 의견으로는 별도의 답변을받을 가치가 있습니다.


답변