HI WELCOME TO SIRIS
Showing posts with label linq. Show all posts
Showing posts with label linq. Show all posts

Understanding LINQ Standard Query Operators

LINQ standard query operators are the methods which help you to write LINQ query. Most of these query methods operate on sequences or collection whose implement the IEnumerable<T> interface or the IQueryable<T> interface. These operators provide query capabilities including filtering, projection, aggregation, sorting and much more.

LINQ Standard Query Operators Sets

LINQ provides two sets of standard query operators, one set operate on objects of type IEnumerable<T> and the other set operate on objects of type IQueryable<T>. Also, these query methods (standard query operators) are static members of the Enumerable and Queryable static classes They are defined as extension methods of the type on which they operate. Hence, they are called either by using static method syntax or instance method syntax.
The query methods which are extended from IEnumerable<T>, operate on in-memory collections. The query methods which are extended from IQueryable<T>, operate on out-of-process memory collections and build an expression tree that represents the query to be performed.

Example for LINQ Query Method Where() Sets

In LINQ to Objects (in-memory collection), LINQ query methods would be used as anonymous method, like Where():
  1. public static IEnumerable<TSource> Where<TSource>(
  2. this IEnumerable<TSource> source, Func<TSource, bool> predicate)
While in LINQ to SQL (out-memory collection), mostly LINQ query methods would be used as expression tree, like Where():
  1. public static IQueryable<TSource> Where<TSource>(
  2. this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate)

LINQ Query Method Execution

The standard query operators are executed based on the value they return. The query methods that return a singleton value (like Average, Sum, Min, Max etc.) then execute immediately. The query methods that return a sequence or collection defer the query execution. The query methods can be chained together in one query.

Writing LINQ Query with the help of Standard Query Operators (LINQ Query Methods)

  1. string sentence = "The quick brown fox jumps over the lazy dog";
  2.  
  3. // Split the string into individual words to create a collection.
  4. string[] words = sentence.Split(' ');
  5.  
  6. // Using query expression syntax.
  7. var query = from word in words
  8. group word.ToUpper() by word.Length into gr
  9. orderby gr.Key
  10. select new { Length = gr.Key, Words = gr };
  11.  
  12. //You can also write above query by using method-based query syntax.
  13. var query1 = words.
  14. GroupBy(w => w.Length, w => w.ToUpper()).
  15. Select(g => new { Length = g.Key, Words = g }).
  16. OrderBy(o => o.Length);
  17.  
  18. //use either query or query1 variable to get result
  19. foreach (var obj in query)
  20. {
  21. Console.WriteLine("\n Words of length {0}:", obj.Length);
  22. foreach (string word in obj.Words)
  23. Console.WriteLine(word);
  24. }
  25.  
  26. /*output:
  27. Words of length 3:
  28. THE
  29. FOX
  30. THE
  31. DOG
  32. Words of length 4:
  33. OVER
  34. LAZY
  35. Words of length 5:
  36. QUICK
  37. BROWN
  38. JUMPS
  39. */

Different types of standard query operators

Operator Type
Operator Name
Aggregate
Aggregate, Average, Count, LongCount, Max, Min, Sum
Concatenation
Concat
Conversions
Cast, OfType, ToList, ToArray, ToLookup, ToDictionary, AsEnumerable
Element
Single, SingleOrDefault, First, FirstOrDefault, Last, LastOrDefault, ElementAt, ElementAtOrDefault
Equality
SequenceEqual
Generation
Repeat, Range, Empty
Grouping
GroupBy
Join
Join, GroupJoin
Ordering
OrderBy, OrderByDescending, ThenBy, ThenByDescending, Reverse
Partitioning
Skip, SkipWhile, Take, TakeWhile
Projection
Select, SelectMany
Quantifier
Contains, All, Any
Restriction
Where
Set
Union, Intersect, Except, Distinct
What do you think?
I hope you will enjoy LINQ Standard Query Operators while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

Difference between ADO.NET and LINQ to SQL

As you know LINQ provides a common query syntax to query any data source and ADO.NET allows you to execute query against any RDBMS like SQL Server, Oracle etc. In this article, I am sharing my view on LINQ and ADO.NET.
ADO.NET
LINQ to SQL
It is a part of .NET Framework since .NET Framework 1.0
It is a part of .NET Framework since .NET Framework 3.5
SqlConnection/OleDbConnection is used for database connectivity.
We can use context for database connectivity.
Difficult to debug and cause syntax errors at run-time.
Easy to debug and cause syntax errors at compile-time.
It has full type checking at run-time and not IntelliSense support in Visual Studio, since it used the T-SQL to query the database.
It has full type checking at compile-time and IntelliSense support in Visual Studio, since it used the .NET Framework languages like C# and VB.
It used T-SQL to query the data to query the database and some other syntax for querying the other data source.
It used LINQ to query the data which provides the uniform programming model (means common query syntax) to query the various data sources.
What do you think?
I hope you will enjoy LINQ and ADO.NET while querying data source. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.

LINQ Inner Join with AND and OR condition

LINQ has a JOIN query operator that provides SQL JOIN like behavior and syntax. As you know, Inner join returns only those records or rows that match or exists in both the tables. The simple inner join example is given below:
  1. DataContext context = new DataContext();
  2. var q = (from pd in context.Products
  3. join od in context.Orders on pd.ProductID equals od.ProductID
  4. orderby od.OrderID
  5. select new
  6. {
  7. od.OrderID,
  8. pd.ProductID,
  9. pd.Name,
  10. pd.UnitPrice,
  11. od.Quantity,
  12. od.Price,
  13. }).ToList();

Inner Join with AND condition

Sometimes, you need to apply inner join with and condition. To write query for inner join with and condition you need to make two anonymous types (one for left table and one for right table) by using new keyword and compare both the anonymous types as shown below:
  1. DataContext context = new DataContext();
  2. var q=from cust in context.tblCustomer
  3. join ord in context.tblOrder
  4. // Both anonymous types should have exact same number of properties having same name and datatype
  5. on new {a=(int?)cust.CustID, cust.ContactNo} equals new {a=ord.CustomerID, ord.ContactNo}
  6. select new
  7. {
  8. cust.Name,
  9. cust.Address,
  10. ord.OrderID,
  11. ord.Quantity
  12. };
  1. // Generated SQL
  2. SELECT [t0].[Name], [t0].[Address], [t1].[OrderID], [t1].[Quantity]
  3. FROM [tblCustomer] AS [t0]
  4. INNER JOIN [tblOrder] AS [t1] ON (([t0].[CustID]) = [t1].[CustomerID]) AND ([t0].[ContactNo] = [t1].[ContactNo])

Note

  1. Always remember, both the anonymous types should have exact same number of properties with same name and Datatype otherwise you will get the compile time error "Type inference failed in the call to Join".
  2. Both the comparing fields should define either NULL or NOT NULL values.
  3. If one of them is defined NULL and other is defined NOT NULL then we need to do typecasting of NOT NULL field to NULL data type like as above

Inner Join with OR condition

Sometimes, you need to apply inner join with or condition. To write query for inner join with or condition you need to use || operator in where condition as shown below:
  1. DataContext context = new DataContext();
  2. var q=from cust in context.tblCustomer
  3. from ord in context.tblOrder
  4. where (cust.CustID==ord.CustomerID || cust.ContactNo==ord.ContactNo)
  5. select new
  6. {
  7. cust.Name,
  8. cust.Address,
  9. ord.OrderID,
  10. ord.Quantity
  11. };
  1. // Generated SQL
  2. SELECT [t0].[Name], [t0].[Address], [t1].[OrderID], [t1].[Quantity]
  3. FROM [tblCustomer] AS [t0], [tblOrder] AS [t1]
  4. WHERE (([t0].[CustID]) = [t1].[CustomerID]) OR ([t0].[ContactNo] = [t1].[ContactNo])
What do you think?
I hope you will enjoy LINQ query with AND and OR conditions while programming with LINQ. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.