Home > Linq > LINQ # 2 – LINQ to Objects

LINQ # 2 – LINQ to Objects


Hi folks,

Today we will go in depth with  LINQ to Objects.

* LINQ to Objects means we can use LINQ to query the objects in a collection.

* We can query any type of object that implements the IEnumerable interface or  IEnumerable<T>(we will go in depth for IEnumerable in next blogs).

* Lists,Arrays and dictionaries are some examples those can be queried by LINQ.

* Advantage of LINQ using on collections or objects is we dont need to use looping to filter values from collections.

Following examples will make the things easy to understand LINQ to objects:-

Example1 from an array collection we want the maximum number so we will have our LINQ query as


   int[] integers = { 1, 6, 2, 27, 10, 33, 12, 8, 14, 5 };
IEnumerable<int> MaxNumber=
from numbers in integers
where numbers >= 10
select numbers; 

Example2 from an array collection we want to fetch only first four numbers.In this case we can use Take() query operator

IEnumerable<int> firstFourNumbers = integers.Take(4);
Example3 The opposite of Take() operator is Skip() operator, which is used to skip the number of items in the collection and retrieve the rest and print them using foreach.
    IEnumerable<int> skipFirstFourNumbers = integers.Skip(4);
Console.WriteLine("Skip first 4 numbers:");
foreach (var num in skipFirstFourNumbers)

Example4 the following code shows how to get the list of numbers from the integers collection until 50 is found.


IEnumerable<int> takeWhileNumber = integers.TakeWhile(num =>
num.CompareTo(50) != 0);
Console.WriteLine("Take while number equals 50");
foreach (int num in takeWhileNumber)

Example5 Similarly, we can skip the items in the collection using SkipWhile(). It uses an expression to bypass the elements in the collection as long as the condition is true

IEnumerable<int> skipWhileNumber = integers.SkipWhile(num =>
num.CompareTo(50) != 0);
Console.WriteLine("Skip while number equals 50");
foreach (int num in skipWhileNumber)


In next blog we will see LINQ on custom built objects collection

Categories: Linq
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: