Getting Started with LINQ – Part 4

Hi Friends,

In today’s section we’ll delve further and see more of LINQ. Let us get started with Take and skip operations.

This will produce me the following output.

13th

Below is the same example while querying db.

14th

Now, let us see select many example.

15th

Cross product example.

16th

Cross product Join example:-

17th

Database cross Join:-

18th

19th

Filtered Association:-

20th

Joining the parent:-

21th

Outer Join – 1st:-

22nnd

Outer Join – 2nd

23rd

Thanks for joining me.

Thanks,
Rahul Sahay
Happy Coding

1,242 total views, no views today

Getting Started with LINQ – Part 3

Hi Friends,

In this section, we are going to delve further. We’ll first start with filtering process. Below is the snippet for the simple filtering process.

This will produce the following result.

8th

Now, let us look at complex style of filtering with multiple where clauses.

9th

Now, let us see the scenario where in we want to skip every 2nd item like shown below.

This will produce the below output.

10th

Let us now query against database. Here, i am reviewing against my movie review database. Here, i am referring Movies table as shown below.

11th

Now, let us consider a scenario where you want to query what IN and NOT-IN scenario as shown below.

12th

Thanks for joining me. We’ll continue same thing in another session. Till then stay tuned and happy coding.

Thanks,
Rahul Sahay
Happy Coding

1,295 total views, no views today

Getting Started with LINQ – Part 2

Hi Friends,

In this section, we’ll proceed further and look different projection strategies. So, the 1st case which i am using here is the Object Initializers. With C# Object Initializers, we can project the same into more complex types. For example, suppose, as a first step in a query, we want to strip vowels from a list of names while still keeping the original versions alongside, for the benefit of subsequent queries. Therefore, we can write as shown below

6th

However, Anonymous Types allow you to structure your intermediate results without writing special classes. So, here we can remove TempProjectionItem as shown below in the example.

7th8th

The let keyword introduces a new variable alongside the range variable. With let, we can write a query extracting strings whose length, excluding vowels, exceeds two characters, as follows:

8th

The compiler resolves a let clause by projecting into a temporary anonymous type that contains both the range variable and the new expression variable. Thanks for joining me. In the next section, we’ll delve further and check other pieces as well. Till then stay tuned and happy coding

Thanks,
Rahul Sahay
Happy Coding

1,313 total views, no views today

Getting Started with LINQ

Hi Friends,

In today’s discussion, we’ll look into LINQ operations. LINQ or Language Integrated Query is a set of language and framework features for constructing type safe queries over local collections or remote data sources. It was introduced in C# 3.0 and framework 3.5.

The basic units of data in LINQ are sequence of elements which actually implements IEnumerable. In the below example,
employees is sequence and “John”,”Dave”,”Black”,”Jack” are elements.

string[] employees = {"John","Dave","Black","Jack"};

A query operator is the one which transforms the sequence. A typical query operator accepts a sequence and emits a transformed output sequence. For, IEnumerable case, we have around 40 query operators. They are also known standard operators.

Let us get started with few simple queries.

Note:- I am using LINQPAD to run these queries. Hence, final statement dump is specific to it. It’s basically used to show the output.

string[] employees = {"John","Dave","Black","Jack","Rahul"};

IEnumerable<string> filtered_emp = employees.Where(n=>n.Length>4);

filtered_emp.Dump("Simple usage of Query");

1st

Since, standard query operators are implemented as static methods, we can directly call Where on employees. Most query operators accept lambda expressions as an argument like here we have n=>n.Length>4.

Now, Let’s look at complex query

string[] employees = {"John","Dave","Black","Jack","Rahul"};

IEnumerable<string> query = employees.Where(n=>n.Contains("a"))
							.OrderBy(n=>n.Length)
							.Select(n=>n.ToLower());

query.Dump("Simple usage of Query");

2nd

here, what it is doing; taking the input, extracts all the strings containing letter a then sorts them by length and then converts the same in lower case. Here, the variable n is privately scoped to each lambda expressions. Here, OrderBy and Select are standard query Operators.

Now, let’s look at Range Variable. The Identifier immediately following the from keyword syntax is called the Range variable. For instance, in below example

from n in new[] { "John","Dave","Black","Jack","Rahul" }
where n.Contains ("a")
select n

3rd

Chaining of query operator is very efficient in many cases like shown below.

string[] names = { "John","Dave","Black","Jack","Rahul" };

IEnumerable<string> query = names
	.Where   (n => n.Contains ("a"))
	.OrderBy (n => n.Length)
	.Select  (n => n.ToUpper());
	
query.Dump();

// same query rewritten progressively:

IEnumerable<string> filtered   = names.Where      (n => n.Contains ("a"));
IEnumerable<string> sorted     = filtered.OrderBy (n => n.Length);
IEnumerable<string> finalone = sorted.Select    (n => n.ToUpper());

filtered.Dump   ("Filtered");
sorted.Dump     ("Sorted");
finalone.Dump ("FinalQuery");

4th

So, as you can see in the above example same final query is achieved in the first expression and again same thing achieved differently by writing the same progressively. Similarly, sometimes we need to keep the natural ordering of numbers as it is.

int[] numbers  = { 10, 9, 8, 7, 6 };

numbers.Take (3)  .Dump ("Take(3) returns the first three numbers in the sequence");
numbers.Skip (3)  .Dump ("Skip(3) returns all but the first three numbers in the sequence");
numbers.Reverse() .Dump ("Reverse does exactly as it says");

5th

Now, in the end there are other important operators which are equally important.

int[] numbers = { 10, 9, 8, 7, 6 };

// Element operators:

numbers.First().Dump ("First");
numbers.Last().Dump ("Last");

numbers.ElementAt (1).Dump ("Second number");
numbers.OrderBy (n => n).First().Dump ("Lowest number");
numbers.OrderBy (n => n).Skip(1).First().Dump ("Second lowest number");

// Aggregation operators:

numbers.Count().Dump ("Count");
numbers.Min().Dump ("Min");

// Quantifiers:

numbers.Contains (9).Dump ("Contains (9)");
numbers.Any().Dump ("Any");
numbers.Any (n => n % 2 != 0).Dump ("Has an odd numbered element");

// Set based operators:

int[] seq1 = { 1, 2, 3 };
int[] seq2 = { 3, 4, 5 };
seq1.Concat (seq2).Dump ("Concat");
seq1.Union (seq2).Dump ("Union");

6th

7th

Thanks for Joining me.

Thanks,
Rahul Sahay
Happy Coding

2,061 total views, no views today

Using LINQPAD

Hi Friends,

In this section, I’ll introduce you with one of my favorite tools i.e. Linqpad. you can download the same from https://www.linqpad.net/. This is extensive tool for .NET programmers. LINQPAD is The .NET Programmer’s Playground. Here, you can do bunch of stuffs like executing LINQ query against SQL, Azure, XML, any object or against any other database. You can add your SQL connection like shown below.

5th

6th

As you can see in the below screen shot, I have simply pulled the movies from my movie review db.

2nd

Then, If i have to see the relationship between the tables, then i can simply go ahead and click on the highlighted link shown in the table above. Like in this case, when i clicked on “MovieReviews”, it produced the below result.

3rd

Behind the scenes it also generated the actual SQL statement as shown below in the screen shot.

4th

You can also execute SQL statement as shown below in the screen shot. only thing you need to change here is the language from the dropdown.

1st

Thanks for joining me.

Thanks,
Rahul Sahay
Happy Coding

2,476 total views, 2 views today