Linq Filtering Operators in C#

Filtering operators are the static extension methods in the IEnumerable class that are used to filter data from a sequence. There are four most commonly used filtering operators in C#:

  • Where
  • Take and Skip
  • TakeWhile and SkipWhile
  • Distinct

Where

The where operator is used to filter the sequence based on some condition which is passed in the form of lambda expression to it in case of fluent syntax and in the form of simple expression in case of Query expression.

Take And Skip

The Take function is used to retrieve the first n elements and discard the rest while Skip function is used to discard the first n elements and retrieve the rest.

TakeWhile & SkipWhile

The TakeWhile operators keeps on retrieving the items from the sequence until a certain condition becomes false. Similarly, SkipWhile keeps on discarding the items in the sequence until a certain condition becomes false and then retrieves the rest.

Distinct

The distinct function is used to retrieve the distinct records from the sequence. All the duplicates are ignored.

The following example demonstrates functionality of all of these filters.

´╗┐using System;
using System.Collections.Generic;
using System.Linq;

namespace CSharpTutorials {
    class Tutorial {
        static void Main() {
            // An array sequence with some items
            int[] randomnums = { 1, 12, 45, 32, 65, 23, 57, 23, 45, 12, 34, 90, 27, 48, 10 };

            // retrieving numbers between 20 and 60
            IEnumerable<int> wherefilter = randomnums.Where(n => n > 20 && n < 60);
            foreach (int n in wherefilter) Console.Write(n+" ");

            //retrieving first 10 numbers
            IEnumerable<int> takefilter = randomnums.Take(10);
            Console.WriteLine("");
            foreach (int n in takefilter) Console.Write(n + " ");

            //skipping first 10 and leaving rest
            Console.WriteLine("");
            IEnumerable<int> skipfilter = randomnums.Skip(10);
            foreach (int n in skipfilter) Console.Write(n + " ");

            //taking while
            Console.WriteLine("");
            IEnumerable<int> takewhilefilter = randomnums.TakeWhile(n=>n<60);
            foreach (int n in takewhilefilter) Console.Write(n + " ");

            //skipping while
            Console.WriteLine("");
            IEnumerable<int> skipwhilefilter = randomnums.SkipWhile(n => n < 60);
            foreach (int n in skipwhilefilter) Console.Write(n + " ");

            //getting distinct
            Console.WriteLine("");
            IEnumerable<int> disticntfilter = randomnums.Distinct();
            foreach (int n in disticntfilter) Console.Write(n + " ");            

            Console.ReadKey();
        }
    }
}

Download the code

<<< LINQ Fluent vs Query SyntaxGrouping Data via GroupBy in LINQ >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .