In this article, I am explaining about LINQ in C#. Basically you can write Linq in C# in two ways,
- Standard syntax which is like calling methods (calling standard LINQ operators as method) directly.
- Query expression syntax which is similar to SQL queries.
For example,
Let’s assume we have 100 numbers in an array and we want to get the result of only odd numbers, so we can use the above two syntaxes as follows,
- Using standard syntax
- var res = listOfNumbers.Where(n => n % 2 != 0);
- Using query expression syntax:
- var res = from n in listOfNumbers where n%2!=0 select n ;
Both these syntax will give the same result, you can choose any syntax based on your comfort level. As you can see the query expression syntax looks similar to SQL statements, but the clause sequence of these two syntaxes are different as follows:
In SQL Query syntax keyword sequence:
SELECT->FROM->WHERE->GROUP BY->HAVING->ORDER BY
In Query expression syntax keyword sequence:
from->[variable name] in [source]->where->groupby->orderby->select
Here you can see that the query expression keywords are all in lower case, written in one-word and there is no having keyword in LINQ expression. Linq uses variables to iterate the source or store the middle result.
With a standard LINQ query we can do a lot of collection data operations, including sorting, filtering, transforming, and advanced operations such as joining and grouping.
The result value of LINQ queries can be a collection or a single value. LINQ Query expressions have operators that are extension methods or static methods, such as Where, OrderBy, Select, GroupBy, Join, etc.
Note
- Always use var to declare the variable which references the LINQ operation result. That’s because sometimes the type LINQ operation result is too complicated and/or too long to spell.
- Avoid writing overly long LINQ queries. Keep the LINQ queries short and clear. This helps with readability.
Where Operator
It accepts a Func<TSource, bool> type parameter, which is the filtering condition. When doing a filtering operation, the Where operator will iterate the source collection and apply this condition to each of the elements, and the elements in the source collection will be passed into the Func<TSource, bool> type delegate one by one. If an element makes the Func<TSource, bool> delegate return true, then that element satisfies the conditions and will be added to the result.
ofType Operator
The OfType operator can help us pick out the instances of a specific child class type.
For example,
- var objects = new Object[] { 8, 6L, 1.54, "Hello", 1, 3 };
- var result = objects.OfType<int>();
- foreach (var item in result) {
- System.Console.WriteLine(item);
- }
The code var result = objects.OfType<int>(); helps to select only all the int type data, here output will be - 8,1,3.
All Operator
It determines whether all the elements in a collection satisfy a condition. It accepts a Func<TSource, bool> type parameter as the condition. The All operator will iterate the collection and pass each of the elements into the Func<TSource, bool> type delegate to get true or false. If all returned values of the delegate are true, that means all of the collection elements satisfy the condition, the All query will return true. If any element produces a false, the All query will return false.
For example,
- var res = StudentRecords.All(s => s.Age > 18);
- System.Console.WriteLine(res);
The above code will check in StudentRecords, for those above age 18; if it's yes then it returns true otherwise it returns false.
Contains Operator
It determines whether a collection contains a specified element and it returns true or false.
For example,
- string[] names = { “Alex”,”Priya”,"Suresh", "Binnu", "Rafnas", "Meenakshi" };
- var res = names.Contains(“Rafnas”);
- System.Console.WriteLine(res);
If you want to check whether the object of the record exists or not:
- var employee = new Employee("Rafnas", “EMP1568”,”IT”);
- var res = employee.Contains(employee);
- System.Console.WriteLine(res);
For that we need to use a comparer to compare the employee object and call another overload version of Contains Operator with the declared comparer.
- public static bool Contains<TSource> (this System.Collections.Generic.IEnumerable<TSource> source, TSource value, System.Collections.Generic.IEqualityComparer<TSource> comparer);
Here comparer parameter is IEqualityComparer<TSource>, so we need to declare a class to implement this interface, and the TScource should be replaced by Employee(class name) as follows,
- class EmployeeComparer : IEqualityComparer<Employee> {
- public bool Equals(Employee x, Employee y) {
- return x.Name == y.Name && x.Gender == y.Gender && x.Rank == y.Rank;
- }
Then we can modify our filter query as below,
- var employee = new Employee("Rafnas", “EMP1568”,”IT”);
- var res = employee.Contains(employee,new EmployeeComparer());
- System.Console.WriteLine(res);
Now the Contains Operator will compare the equality of the employee records using our customized comparison logic.
Distinct Operator
It is used to keep unique elements of the collection and removes duplicate elements.
For example,
- string[] names = { "Suresh", "Binnu", "Rafnas",”Binnu”, "Meenakshi",”Rafnas” };
- var distinctResult = names.Distinct();
- Console.WriteLine(string.Join(",", distinctResult));
-
- /OutPut: Suresh, Binnu, Rafnas, Meenakshi
Intersect Operator
It is used to return the set intersection; that means elements appear in both collections.
For example,
- string[] set1 = { "Suresh", "Rafnas", ”Alex”, "Suresh", };
- string[] set2 = { "Ahalya", "Rafnas", "Meenakshi", ” Alex” };
-
- var intersectResult = set1.Intersect(set2);
- Console.WriteLine(string.Join(",",intersectResult));
-
-
Except Operator
It is used to return the set difference; that means elements of one collection that do not appear in a second collection.
For example,
- string[] set1 = { "Suresh", "Rafnas", ”Alex”, "Suresh", };
- string[] set2 = { "Ahalya", "Rafnas", "Meenakshi", ” Alex” };
-
- var exceptResult = set1.Except(set2);
- Console.WriteLine(string.Join(",",exceptResult));
-
-
Union Operator
It is used to return the set union; that means unique elements that appear in either of two collections.
For example,
- string[] set1 = { "Suresh", "Rafnas", ”Alex”, "Suresh", };
- string[] set2 = { "Ahalya", "Rafnas", "Meenakshi", ” Alex” };
-
- var unionResult = set1.Union(set2);
- Console.WriteLine(string.Join(",",unionResult));
-
-
Concatenation Operator
It is used to return all elements from two collections with duplicate elements.
For example,
- string[] set1 = { "Suresh", "Rafnas", ”Alex”, "Suresh", };
- string[] set2 = { "Ahalya", "Rafnas", "Meenakshi", ” Alex” };
-
- var concatResult = set1.Concat(set2);
- Console.WriteLine(string.Join(",",concatResult));
-
-
Sorting Operators
These operators are used to order the elements of a sequence based on one or more attributes.
- OrderBy - it is used to order the elements in ascending order
- OrderByDescending - it is used to order the elements in descending order
- ThenBy - it is used to perform secondary sort in ascending order
- ThenByDescending - it is used to perform secondary sort in descending order
- Reverse - it is used to reverse the order of elements in a collection.
Note
All of the above five operators can provide an extra IComapare<TKey> type parameter to override the default sorting method.