Naveen's Weblog

Bridge to future

Samples for all Linq functions at one place

Posted by codingsense on September 11, 2008

I had many confusions when i used linq for the first time. For each function i searched its usage and then used it. It was pretty time consuming. So i decided to make a sample that will explain almost all linq functions at one place.

Here comes the sample.
Download sample – 45.2Kb

int[] arrNumbers1 = { 1, 4, 8, 4, 15, 12, 15};
int[] arrNumbers2 = { 2, 9, 3, 5, 8, 18, 15 };

//The LINQ aggregate operators allow you to perform simple math
//operations over the elements in a collection in a sequence

//1.Take min of the elements in a collection
int ArrgrNum = arrNumbers2.Aggregate((s, t) => Math.Min(s, t));

//2.Lets reverse a string
string sentence = "I went with her for a walk in evening";
// Split the string into individual words.
string[] words = sentence.Split(' ');
// Join each word to the beginning of the new sentence to reverse the word oder.
string reverse = words.Aggregate((CurrentWord, next) => next + " " + CurrentWord);

//3.Lets check with an example to find the factorial of a given Number.
int N = 5;
IEnumerable intSequence = Enumerable.Range(1, N);
int agg = intSequence.Aggregate((av, e) => av * e);
Console.WriteLine("{0}! = {1}", N, agg);

//All<> does not return a list of the items in the collection.
//It returns a bool indicating if all the items in the list match an expression.

//We will first check whether all NO's in the array are even or not
var AllEven = arrNumbers1.All(temp => temp % 2 == 0);

//Here we check all the numbers in the array are greater than 1 or not
var AllGreater = arrNumbers2.All(Greater => Greater > 1);

//Any is reverse of All, it checks like "If any element satisfies the condition return true"
var AnyEven = arrNumbers1.Any(temp => temp % 2 == 0);

var AvgNum =  arrNumbers1.Average();

//conditional avereage
//This takes the average of all elemets in an array whose value are greater than 8
//If less then it will replace it with 8 and take the average
var AvgOther = arrNumbers1.Average(temp => temp > 8 ? temp : 8);

var strArray =  arrNumbers1.Cast();

//Concatenates both the array
var ConcatArr = arrNumbers2.Concat(arrNumbers1);

bool hasElement = arrNumbers1.Contains(2);

//Removes the duplicates and returns only distinct elements
int[] DistinctOnly = arrNumbers1.Distinct().ToArray();

//*********ELement at********
//Returns Element at give index
var ElementAt = arrNumbers2.ElementAt(3);

//returns the element if its present at the given index
//Or returns its default eg: int 0, stirng empty
var ElementAtOrDef = arrNumbers2.ElementAtOrDefault(15);

//*********Except eg***********
//Selects the elements other than the specified in parameter
var ExceptEg = arrNumbers2.Except(arrNumbers1);
var ExceptEg1 = arrNumbers1.Except(Enumerable.Range(1,5));

//Returns the first element that matches the condition
var FirstEle = arrNumbers1.First(temp => temp > 8);

//Returns the first element that matches the condition or
//returns the default value
var FirstOrDef = arrNumbers1.FirstOrDefault(temp => temp > 15);

//Gets value of the element at given Index
var GetValuesAtIndex = arrNumbers1.GetValue(3);

//Returns the elements those are comman in both the arrays
var IntersectOfBoth = arrNumbers1.Intersect(arrNumbers2);

//Gives the last element matching the condition specified in the parameter
var Last = arrNumbers2.Last(temp => temp > 6);

//Gives the last element matching the condition specified in the parameter
//If not found then returns the default value
var LastOrDef = arrNumbers2.LastOrDefault(temp => temp > 150);

//Returns the max element in the collection
var MaxEle = arrNumbers2.Max();

//Returns the min element in the collection
var MinEle = arrNumbers2.Min();

//Orders the list in ascending order
var OrderBY = arrNumbers2.OrderBy(x => x);

//ORders the list in Descendig order
var DscArray = arrNumbers2.OrderByDescending(x => x);

//Reverses the list
var ReverseArr = arrNumbers2.Reverse();

//Selects the element that satisfies the given condition
//here we will select all elements as power of 2
var SelectArr = arrNumbers2.Select(ele => Math.Pow(2,ele));

//If both the arrays are equal return true else return false
bool AreEqual = arrNumbers2.SequenceEqual(arrNumbers1);

//********Set Value**********
//Sets the given value to the element in the collection at given index
arrNumbers1.SetValue(100, 2);

//Returns the index of the element whose value is equal to the given parameter
//If it has 0 or 2 elements with same value then it gives an error.
int SingleIndex = arrNumbers1.Single(imp => imp == 1);

//Returns the index of the element whose value is equal to the given parameter
//If no element with the given value then it returns the default
int SingleDef = arrNumbers1.SingleOrDefault(imp => imp == 10);

//Skip first 3 elements and returs other elements
var SkipFirstElements = arrNumbers2.Skip(3);

//Here in this sample we will extract only those no that are
//divisible by 3
var SkipConditional = arrNumbers1.SkipWhile(num => num % 3 != 0);

//Get the sum of an array
var SumOfArray = arrNumbers1.Sum();

//Its just the reverse operation of skip
//here it takes the first n elements specified in the parameter
var Take = arrNumbers2.Take(3);

//Takes only those elements that are not divisible by 3
var TakeWhile = arrNumbers2.TakeWhile(num => num % 3 != 0);

//converts the IEnumerable ouput an array of type specified in T
int[] IntArray = arrNumbers1.Take(3).ToArray();

//Union of both the arrays - only unique
int[] UnionOfBoth = arrNumbers1.Union(arrNumbers2).ToArray();

//Select elements those are greater than 5
int[] GreaterThan5 = arrNumbers2.Where(x => x > 5).ToArray();

Any suggestions are wide open.

Happy learning 🙂


3 Responses to “Samples for all Linq functions at one place”

  1. Zorab S said

    Good Article .
    is LINQ to system resources possible?
    If yes can u post a sample.

    • Naveed Butt said

      Infact, it is not straight forward, but yes, look into WMI (Windows Management Instrumentation) for C#.

  2. codingsense said

    Thanks for writing zorab
    I dint get exactly what you mean by system resources
    but i just had a sample in which i used linq with system files and processes
    check if it helps

    If you want any other, please specify i will post it for you.


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: