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

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

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<string> 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

Code Snippets in Visual Studio

This post gives you idea about Code Snippets in Visual Studio and how you can use them. Code snippets in Visual Studio are useful in reducing typing effort required to input your code. Code Snippets help in various ways in simplifying your work if you can remember to use them instead of typing the actual code. Code Snippets are present in Visual Studio 2005, 2008 & 2010

To use code snippets, instead of typing the code you will type a shortcut, actually a word and press Tab key, to insert the actual code to which the shortcut is linked with.

For example, to type the below code..

for (int i = 0; i < length; i++)
{

}

You can type "for" and then press Tab..you will then get the code inserted into the code window as shown below..

2

3

Now you can see that “i” is highlighted, this means you can type a name for the loop variable, once you renamed it, you can press Tab to select “length” and rename it or specify what should be there, like, list.Count, etc. Once done, press enter to place the cursor inside the for loop braces.

So as you can see whenever you need to write a for loop you can use this code snippet and save time. There are many code snippets you can use.

Also you can right click code editor and select Insert Snippet...(Ctrl+K, Ctrl+X) and choose the snippet you need from the list. You can also select set of code lines and right click and select Surround With...(Ctrl+K, Ctrl+S) option to put the selected code into the snippet that you will insert, like, a try..catch block.

Bookmark / Share