Partitioning Data Using LINQ

Posted by: Suprotim Agarwal , on 11/16/2009, in Category LINQ
Views: 42799
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
Skip Operator
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
SkipWhile
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
Take Operator
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
TakeWhile
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.
 If you liked the article,  Subscribe to my RSS Feed or Subscribe Via Email 
 
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles
Suprotim Agarwal, ASP.NET Architecture MVP, MCSD, MCAD, MCDBA, MCSE, is the CEO of A2Z Knowledge Visuals Pvt. He primarily works as an Architect Consultant and provides consultancy on how to design and develop .NET centric database solutions.

Suprotim is the founder and primary contributor to DotNetCurry, DNC .NET Magazine, SQLServerCurry and DevCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls. and is authoring another one at The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by karthik on Monday, December 30, 2013 3:39 AM
Good article

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel