How to flatten a list using LINQ C#?

CsharpServer Side ProgrammingProgramming

Flattening a list means converting a List<List<T>> to List<T>. For example, let us consider a List<List<int>> which needs to be converted to List<int>.

The SelectMany in LINQ is used to project each element of a sequence to an IEnumerable<T> and then flatten the resulting sequences into one sequence. That means the SelectMany operator combines the records from a sequence of results and then converts it into one result.

Using SelectMany

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         List<List<int>> listOfNumLists = new List<List<int>>{
            new List<int>{
               1, 2
            },
            new List<int>{
               3, 4
            }
         };
         var numList = listOfNumLists.SelectMany(i => i);
         Console.WriteLine("Numbers in the list:");
         foreach(var num in numList){
            Console.WriteLine(num);
         }
         Console.ReadLine();
      }
   }
}

Output

Numbers in the list:
1
2
3
4

Using Query

Example

 Live Demo

using System;
using System.Collections.Generic;
using System.Linq;
namespace DemoApplication{
   public class Program{
      static void Main(string[] args){
         List<List<int>> listOfNumLists = new List<List<int>>{
            new List<int>{
               1, 2
            },
            new List<int>{
               3, 4
            }
         };
         var numList = from listOfNumList in listOfNumLists
         from value in listOfNumList
         select value;
         Console.WriteLine("Numbers in the list:");
         foreach(var num in numList){
            Console.WriteLine(num);
         }
         Console.ReadLine();
      }
   }
}

Output

Numbers in the list:
1
2
3
4
raja
Published on 24-Sep-2020 16:02:39
Advertisements