Alex Rivera | Logout

Use linq to break up list<t> into lots of list<t> of n length?

Asked 2011-03-07T03:18:59.307
24

Possible Duplicate:
How can I split an IEnumerable<String> into groups of IEnumerable<string>

I have a list that I would like to break into groups of 10.

If I have an object

List<Person> allPendingPersons 

that is of length m.

Is there an elegant way in LINQ to break up allPendingPersons into one or more List objects that all have a up to 10 Persons?

Edit
Report

1 Answer

0

Is there an elegant way in LINQ

The elegant way is not very performant. Here is a more performant way...

    public static List<List<T>> Chunk<T>(
      this List<T> theList,
      int chunkSize
    )
    {
        if (!theList.Any())
        {
            return new List<List<T>>();
        }

        List<List<T>> result = new List<List<T>>();
        List<T> currentList = new List<T>();
        result.Add(currentList);

        int i = 0;
        foreach(T item in theList)
        {
            if (i >= chunkSize)
            {
                i = 0;
                currentList = new List<T>();
                result.Add(currentList);
            }
            i += 1;
            currentList.Add(item);
        }
        return result;
    }
answered 2011-03-07T15:26:57.603

Your Answer