C# Tips & Tricks #23 – Split List into multiple List

In this C# tips & tricks post , we will look at a simple usage of LINQ in C# to split list into multiple list with the extension method.

How to Split list into multiple list in C# ?

Assume that you have a ListSize which you will need to split the list. For example , if you have a list with 4 elements and you wish to convert them in to 4 different lists. Here’s a code snippet demonstrating how you can do that.

public static class TestExtensionMethod
{
        public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> sourceList, int ListSize)
        {
            while (sourceList.Any())
            {
                yield return sourceList.Take(ListSize);
                sourceList = sourceList.Skip(ListSize);
            }
        }
}

Here’s the full code snippet.

using System;
using System.Collections.Generic;
using System.Linq;

namespace DeveloperPublish
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            List<string> Names = new List<string>
            { "Senthil Kumar" , "Ashwini Sambandan" , "Norton Stanley" , "Santhosh"
            };
            var result = Names.Split(1).ToList();
            Console.WriteLine(result[0]);

            Console.ReadLine();
        }

    }

    public static class TestExtensionMethod
    {
        public static IEnumerable<IEnumerable<T>> Split<T>(this IEnumerable<T> sourceList, int ListSize)
        {
            while (sourceList.Any())
            {
                yield return sourceList.Take(ListSize);
                sourceList = sourceList.Skip(ListSize);
            }
        }
    }
}

Output

How to Split list into multiple list in C# ?

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...