Small sample methods on LINQ

There are several samples on LINQ provided by Microsoft.

If you install Visual Studio 2008 and .Net Framework 3.5 in your machine, you can find these samples in the following path
C:\Program Files\Microsoft Visual Studio 9.0\Samples

You can find the same LINQ samples in the following Microsoft website

http://msdn.microsoft.com/en-us/vcsharp/aa336746.aspx

Some sample methods on LINQ

This sample uses where to find all pencils that are out of stock.

public void SampleMethod1() 
{
List pencils = GetAllPencils();

var soldOutPencils =
from p in pencils
where p.UnitsInStock == 0
select p;

Console.WriteLine("Sold out Pencils:");
foreach (var pencil in soldOutPencils) {
Console.WriteLine("{0} is sold out!", pencil.PencilName);
}
}




Sold out Pencils:
pencil1 is sold out!
pencil2 is sold out!
pencil3 is sold out!
pencil4 is sold out!
pencil5 is sold out!

This sample uses select to produce a sequence of the uppercase and lowercase versions of each word in the original array.
public void SampleMethod2() 
{
string[] words = { "hiMasAgAR", "SagAR", "kuTIkuPPala HimaSAGar" };

var upperLowerWords =
from w in words
select new {Upper = w.ToUpper(), Lower = w.ToLower()};

foreach (var ul in upperLowerWords) {
Console.WriteLine("Uppercase: {0}, Lowercase: {1}", ul.Upper, ul.Lower);
}
}




Uppercase: HIMASAGAR, Lowercase: himasagar
Uppercase: SAGAR, Lowercase: sagar
Uppercase: KUTIKUPPALA HIMASAGAR, Lowercase: kutikuppala himasgar

This sample uses TakeWhile to return elements starting from the beginning of the array until a number is hit that is not less than 6.
public void SampleMethod3() 
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

var firstNumbersLessThan6 = numbers.TakeWhile(n => n < 6);

Console.WriteLine("First numbers less than 6:");
foreach (var n in firstNumbersLessThan6)
{
Console.WriteLine(n);
}
}




First numbers less than 6:
5
4
1
3

This sample uses group by to partition a list of pens by category.
public void SampleMethod4()
{
List pens = GetAllPens();

var penGroups =
from p in pens
group p by p.Category into g
select new { Category = g.Key, Pens = g };

Consol.WriteLine(penGroups, 1);
}


Regards
Himasagar Kutikuppala


Comments

Author: VMRK02 Sep 2008 Member Level: Gold   Points : 0

the article is too good



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: