How to Split List into Sub list in C# using LINQ ?

Published on June 7, 2015 by abundantcode

Filed under C#

Last modified June 7, 2015

Print this page

rate 1 star rate 2 star rate 3 star rate 4 star rate 5 star
Your rating: none, Average: 3.5 (2 votes)

This article have been viewed 6441 times

If you want to split the generic list in to sub list in C# , one of the simplest way is to use LINQ (Language Integrated Query). Below is a code sample demonstrating this feature.

How to Split List into Sub list in C# using LINQ ?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace AbundantcodeApp
{
    class Program
    {
        static void Main(string[] args)
        {

            List<string> strLst = new List<string>();
            strLst.Add("Android Development");
            strLst.Add("Windows Phone Development");
            strLst.Add("Abundantcode Programming");
            var result = Split(strLst);
            Console.ReadLine();
        }

        public static List<List<string>> Split(List<string> input)
        {
            return input.Select((item1, index) => new { Index = index, Value = item1 })
                .GroupBy(x => x.Index / 3)
                .Select(x => x.Select(v => v.Value).ToList())
                .ToList();
        }


    }
    
}

Leave a Comment


x

You might be Interested in these Posts

How to Create an Empty array without defining the size in C# ?

When we create an array in C# , we tend to define the size of the array as shown below. String[] st...

How to Get the number of elements in ArrayList in C# ?

Here's the code that demonstrates how one can get the total number of elements contained in the Arra...

How to Check if the ArrayList is read-only in C# ?

There are times when you would use the read-only wrapper in order to prevent modifying the ArrayList...