LINQ in c# : concise guide
LINQ (Language Integrated Query) is a uniform query syntax in C# to retrieve data from different sources and formats. LINQ generalizes the query interface by eliminating most of the hurdles to make raw data query/operation ready and as a result, LINQ returns an object for easy accessibility.
Required Namespace
using System;
using System.Linq;
using System.Collections.Generic;//for method LINQ
Three Parts of a Query Operation
At the time of actual query execution of dataQuery executes & creates IEnumerable<T> as result set which replaces dataQuery in foreach.
// 1. Obtain the data source
int[] dataList = new int[7] { 0, 1, 2, 3, 4, 5, 6 };// 2. Query creation
var dataQuery = from num in dataList
where (num % 2) == 0
select num;// 3. Query execution
foreach (int num in dataQuery)
{
Console.Write("{0,1} ", num);
}
Two ways to write LINQ
List<string> cityList = new List<string>()
{“Mumbai”, “Pune”, “Chennai”, “Delhi”};// way 1 - query syntax
var dataList1 = from city in cityList
where city.Contains(“a”)
select city;
foreach (var item in dataList1)
{
Console.WriteLine(item);
}// way 2 - method syntax (using extension method and lambda)
var dataList2 = cityList.Where(x => x.Contains(“a”)).Select(x => x);
foreach (var item in dataList2)
{
Console.WriteLine(item);
}
Examples of LINQ
Where, OrderBy
var list1 = new List<string> { “Mike”, “John”, “Jane”, “Harvey”, “Rachel” };//query syntax
var dataList1 = from x in list1
where x.Contains("a")
orderby x ascending
select x;//method syntax
var dataList2 = list1.Where(x => x.Contains("a"))
.OrderBy(x => x)
.Select(x => x);
Aggregate Function
int[] data = { 10, 20, 30, 40, 50 };
int result = data.Sum();//150
int result2 = data.Max();//50
int result3 = data.Min();//10
double result4 = data.Average();//30
Compare Multiple data lists
//compare two lists
var list1 = new List<int> { 5, 10, 15, 20, 25, 30, 35, 40 };
var list2 = new List<int> { 10, 20, 30, 40, 50 };
//query syntax
var dataList1 = from x in list1
from y in list2
where x < y
select new { x, y };
I hope you find something useful. If you like this article then please clap for me…👏👏👏