{LINQ Samples} Sample 2 - Display list of items in a string array based on item(element) length

Note: These LINQ samples are written keeping the beginner in mind so the code is made as simple as possible.

LINQ Samples series intro: LINQ-Language INtegrated Query is a great .Net language feature, to simple put, it allows you to query data objects in the way you query database tables using english sentence like syntax.

 

string[] strArray = new string[] { "apple", "orange", "grape", "lemon" };


IEnumerable s = from x in strArray 
                        where x.Length == 6 
                        select x; 
Console.WriteLine(s);

 

Output:

orange

 

First “x” transforms itself as an item in the strArray and the LINQ code runs for each element in strArray, the “where” section is used to specify the condition, which here uses the x(an element of the array) and “select” section is where the final output of the LINQ query is returned, here it is the array elements.

Bookmark / Share

{Beginner C# samples} - What is the use of ‘var’ keyword in C# ?

Note: These beginner C sharp samples codes are written keeping the beginner in mind so the code is made as simple as possible.

Starting from C# 3.0 the “var” keyword is included. var is used when you want to declare a variable’s type implicitly instead of explicit.

Explicit declaration:

string s = “Great”;

Implicit declaration:

var s = “Great”;

In compile time the datatype is determined implicitly by the compiler.

Will explain more about this in the LINQ series later.

Bookmark / Share

{LINQ Samples} Sample 1 - Search a string array using LINQ

Note: These LINQ sample codes are written keeping the beginner in mind so the code is made as simple as possible.

LINQ Samples series intro: LINQ-Language INtegrated Query is a great .Net language feature, to simple put, it allows you to query data objects in the way you query database tables using english sentence like syntax.

 

string[] strArray = new string[] { "apple", "orange", "grape", "lemon" };

IEnumerable s = from x in strArray 
                        where x.Contains("ap") 
                        select x; 
Console.WriteLine(s);

Output:

apple

grape

 

As this is the first LINQ sample I am explaining a little bit about how the code executes internally.

Here “x” transforms itself as an item in the strArray and the LINQ code runs for each element in strArray, the “where” section is used to specify the condition, which here uses the x(an element of the array) and “select” section is where the final output of the LINQ query is returned, here it is the array elements.

Bookmark / Share