Partitioning Data Using LINQ
Posted by: Suprotim Agarwal ,
on 11/16/2009,
in
Category LINQ
Abstract: We often come across requirements where data needs to be partitioned into two parts and then return one of the parts. The Partition Operators in LINQ helps you partition data. In this article, we will see how to use these operators to partition collections
Partitioning Data Using LINQ
We often come across requirements where data needs to be partitioned into two parts and then return one of the parts. The Partition Operators in LINQ helps you partition data. These operators are Skip, SkipWhile, Take and TakeWhile. In this article, we will see how to use these operators to partition collections. Malcolm Sheridan had posted a cool article demonstrating a practical usage of the Skip and Take operators. You can read it over here Efficient Server Side Paging with the ASP.NET GridView Control. You can also read more about Partition Operators over here
For demonstration purposes, we will take the Person class as a sample whose definition is as shown below:
C#
class Program
{
static void Main(string[] args)
{
List<Person> collectionOne = new List<Person>();
collectionOne.Add(new Person() { ID = 1, Name = "Jack" });
collectionOne.Add(new Person() { ID = 2, Name = "Julian" });
collectionOne.Add(new Person() { ID = 3, Name = "David" });
collectionOne.Add(new Person() { ID = 4, Name = "Kathy" });
collectionOne.Add(new Person() { ID = 5, Name = "Jennifer" });
collectionOne.Add(new Person() { ID = 6, Name = "Billy" });
}
static void PrintConsole(List<Person> per)
{
foreach (Person p in per)
{
Console.WriteLine("{0} {1}", p.ID, p.Name);
}
Console.ReadLine();
}
}
class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
VB.NET
Module Module1
Sub Main()
Dim collectionOne As New List(Of Person)()
collectionOne.Add(New Person() With {.ID = 1, .Name = "Jack"})
collectionOne.Add(New Person() With {.ID = 2, .Name = "Julian"})
collectionOne.Add(New Person() With {.ID = 3, .Name = "David"})
collectionOne.Add(New Person() With {.ID = 4, .Name = "Kathy"})
collectionOne.Add(New Person() With {.ID = 5, .Name = "Jennifer"})
collectionOne.Add(New Person() With {.ID = 6, .Name = "Billy"})
End Sub
Sub PrintConsole(ByVal per As List(Of Person))
For Each p As Person In per
Console.WriteLine("{0} {1}", p.ID, p.Name)
Next p
Console.ReadLine()
End Sub
End Module
Class Person
Private privateID As Integer
Public Property ID() As Integer
Get
Return privateID
End Get
Set(ByVal value As Integer)
privateID = value
End Set
End Property
Private privateName As String
Public Property Name() As String
Get
Return privateName
End Get
Set(ByVal value As String)
privateName = value
End Set
End Property
End Class
The PrintConsole() method accepts a List<> and prints it on the console.
Let us now explore the Partition Operators.
Skip – The ‘Skip’ Operator skips elements to a specified position in a sequence and returns the remaining elements. Let us see how to use the Skip operator
In this example, we will be skipping the first two elements in the List and return the remaining elements
C#
var p1 = collectionOne.Skip(2).ToList();
PrintConsole(p1);
VB.NET
Dim p1 = collectionOne.Skip(2).ToList()
PrintConsole(p1)
Output
SkipWhile – The ‘SkipsWhile’ operator skips elements in a sequence as long as the specified condition remains true and then returns the remaining elements.
In this example, we will be skipping the elements in the List till the name “Kathy” and return the remaining elements along with “Kathy”
C#
var p2 = collectionOne.SkipWhile(x => x.Name != "Kathy").ToList();
PrintConsole(p2);
VB.NET
Dim p2 = collectionOne.SkipWhile(Function(x) x.Name <> "Kathy").ToList()
PrintConsole(p2)
Output
Take – The ‘Take’ operator grabs elements to a specified position in the sequence and returns the grabbed elements
In this example, we will grab the first two elements in the List
C#
var p3 = collectionOne.Take(2).ToList();
PrintConsole(p3);
VB.NET
Dim p3 = collectionOne.Take(2).ToList()
PrintConsole(p3)
Output
TakeWhile - The ‘TakeWhile’ operator grabs elements to a specified position in the sequence till the specified condition is true and returns the grabbed elements
In this example, we will grab the elements till ID<=4 in the List
C#
var p4 = collectionOne.TakeWhile(x => x.ID <= 4).ToList();
PrintConsole(p4);
VB.NET
Dim p4 = collectionOne.TakeWhile(Function(x) x.ID <= 4).ToList()
PrintConsole(p4)
Output
In this article, we saw how to use LINQ operators to partition data. I hope you found this article useful and I thank you for viewing it.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of
DotNetCurry,
DNC Magazine for Developers,
SQLServerCurry and
DevCurry. He has also authored a couple of books
51 Recipes using jQuery with ASP.NET Controls and
The Absolutely Awesome jQuery CookBook.
Suprotim has received the prestigious Microsoft MVP award for Sixteen consecutive years. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that offers Digital Marketing and Branding services to businesses, both in a start-up and enterprise environment.
Get in touch with him on Twitter @suprotimagarwal or at LinkedIn