LINQ is language integrated query. Below are simple example of LINQ expression and syntax. We will query an array of string.
- Linq Chapter 1 – Split string to list of strings.
- Linq Chapter 2 – Remove duplicates from list.
- Linq Chapter 3 – Linq Where Clause.
- Linq Chapter 4 – Linq Group by multiple clause.
- Linq Chapter 5 – Linq Inner Join query.
- Linq Chapter 6 – Linq Distinct list.
- Linq Chapter 7 – Linq OfType Method.
All above chapters are enough for beginners to learn and understand Linq query.
Apart from above examples. I recommend you to download LinqPAD. It’s third party free software tool. You can write Linq query and see underlined SQL statements generated by your Linq query.
//Create an array of Strings
string[] arr = "A,B,C,D,E,F,U,X,Y,Z".Split(",".ToCharArray());
//Populate listbox with array of strings
ListBox1.DataSource = arr;
//Bind array of strings to Listbox
ListBox1.DataBind();
//Using linq syntex we will query an array of strings and find the word "S" and "M"
var query = from alphabet in arr
where (alphabet == "S" || alphabet == "M")
select alphabet ;
// A query body must end with a select clause or a group clause
foreach(var alpha in query)
{
Response.Write(alpha+" "); //Write the word found.
}
Linq Where extension.
System.Linq.Enumerable has a extension method called where.
(new[] {"Ram", "Sham", "Gopal","Mahesh"} ).Where (n => n.Length >= 4)
Output
Sham
Gopal
Mahesh
Inside of the where expression you can see "n => n.Length >=4", It is read as "n goes to n.length greater than or equal to 4". The operator => is read as "Goes to". It's a lambda expression. We are expecting to get result of array containing elements with length greater than or equal to 4.