Use Linq to Split a List: Skip and Take
- Sean
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.
- Paging and the Entity Framework, Skip, and Take Part 3
- Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq… Speed Test/Texas Tornado Match
- Linq Join Extension Method and How to Use It…
- Linq Extension Methods Versus Linq Query Language… DEATHMATCH
Categories
Related Posts
- Paging and the Entity Framework, Skip, and Take Part 3
- Dictionary Index Lookup Vs Contains Key Vs List Contains Vs Linq… Speed Test/Texas Tornado Match
- Linq Join Extension Method and How to Use It…
- Linq Extension Methods Versus Linq Query Language… DEATHMATCH
Recent Posts
- WPF: Inherit Style From Style. BasedOn Is Your Friend
- WPF: Hide Built in Header Bar For an Open Window
- Spark View Engine, ASP.Net MVC, and You
- ByATool.com Is Looking For Writers
Reviews
Random Quote
Sean: You make me sick.
Curtiss: Maybe you shouldn’t have bit my leg then, God dammit.



April 27th, 2009 - 16:37
Great work.