- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to flatten a list using LINQ C#?
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
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
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
Advertisements