Say what? Ok this is simple, and probably useless for most people but I thought I’d post it anyhow. Basically, say you have a huge list of something and you need to split it into smaller lists of something. This might be the case if you want to use parameterized SQL or something like HQL to send in a list full of somethings. Problem? Sql Server will only allow so many parameters to be sent in. Now you could send in a string in some cases, but meh. Kind of sloppy. So what do you do? You come here and you gank this method.
public static IList<IList<T>> SplitList<T> (IList<T> listToSplit, Int32 countToTake) { IList<IList<T>> splitList = new List<IList<T>>(); Int32 countToSkip = 0; do { splitList.Add(listToSplit.Skip(countToSkip) .Take(countToTake).ToList()); countToSkip += countToTake; } while (countToSkip < listToSplit.Count); return splitList; }
Pretty simple. It takes in a list of whatever and gives you back a list of lists of whatever. The fun part is using Skip and Take. Two methods I have come to love.
Basically you start out skipping nothing and taking a set amount… say 2000. Next time through, you start by skipping 2000 and taking the next 2000. Beauty of Take is it won’t just die on you if you don’t have enough items. It’ll just grab what’s left. Yay for take.