LINQ Basic

LINQ BASIC
I am starting from this mail to show the technical skills to work with LINQ .
The following is a very basic LINQ Query Expression Example:

string[] strCities = { "Mumbai", "Delhi", "Surat", "Chennai", "Ahemdabad", "Jaipur" };

IEnumerable strResult = from city in strCities
select city.ToUpper();

grdLinqBasic.DataSource = strResult;
grdLinqBasic.DataBind();

In the above Example I am using the array of string and then using LINQ query expression against the array. I am also applying a string operation in the query itself, which help us to modify the result in the query itself.
LINQ queries return results of type: IEnumerable
Where is determined by the object type of the “select” clause of the query. In the above sample “city” is string. So the above example have the IEnumerable type is “string”.
LINQ is STORNGLY-TYPED
It means we can have compile-time checking of our queries, unlike SQL statements where we can find any error only at runtime. This means you will be able to check your code during when u r coding that it is correct or not.
In the next example we will see how it’s strongly-typed
I am creating the Location class with 3 member Country, Distance and City
public class Location
{
private string _country;
private int _distance;
private string _city;

public string Country
{
get{
return _country;
}
set{
_country=value;
}
}

public int Distance
{
get{
return _distance;
}
set{
_distance=value;
}
}

public string city
{
get{
return _city;
}
set{
_city=value;
}
}
}
Now I am creating one more class and using Travelorganizer, It has one member PlaceVisited and its returning ainstance of Location class.
In the following class there’s a new feature of c# 3.0 is used that allow me to create a class instances, and then allow me to setting properties on them.
Its very useful when we are working with anonymous type.
public class Travelorganizer
{
public List PlacesVisited
{
get
{
List cities = new List
{
new Location{ city="London", Distance=4789, Country="UK"},
new Location{ city="Amsterdam", Distance=4869, Country="Netherland"},
new Location{ city="San Francisco", Distance=684, Country="USA"},
new Location{ city="Las Vegas", Distance=872, Country="USA"},
new Location{ city="Boston", Distance=2488, Country="USA"},
new Location{ city="Raleigh", Distance=2363, Country="USA"},
new Location{ city="Chicago", Distance=1733, Country="USA"},
new Location{ city="Charleston", Distance=2421, Country="USA"},
new Location{ city="Helsinki", Distance=4771, Country="Finland"},
new Location{ city="Nice", Distance=5428, Country="France"},
new Location{ city="Dublin", Distance=4527, Country="Ireland"},

};

return cities;
}
}
}

Now I will generate list of Cities and countrywhich are more than 1000 miles away from seattle.
Travelorganizer travel = new Travelorganizer();

grdLinqRicherCollection.DataSource = from location in travel.PlacesVisited
where location.Distance > 1000
orderby location.Country, location.city
select location;

grdLinqRicherCollection.DataBind();
The HTML Part will be for gridview

<h1>Cities and their Distances</h1>
<asp:gridview id="grdLinqRicherCollection" autogeneratecolumns="false" runat="server">
<columns>
<asp:boundfield headertext="Country" datafield="Country">
<asp:boundfield headertext="City" datafield="City">
<asp:boundfield headertext="Distance from Seattle" datafield="Distance">
</columns>
</asp:GridView>

How Linq is strongly-typed is we can check in the above example if you type “sity” instead of “city” then the compiler wold catch it. In SQL It will not.
Standard Query Operators and LINQ
In the following Linq code I am using the Skip() and Take() operator with the LINQQuery Expression which gives the developer freedom to extract data from the result of query and it also decrease the database query processing.
Travelorganizer travel = new Travelorganizer();
grdLinqRicherCollection.DataSource = (from location in travel.PlacesVisited
orderby location.Distance descending
select location).Skip(1).Take(5);

grdLinqRicherCollection.DataBind();

In the above query I wanted the list of cities in order of distance and list the 2nd to 6th farthest away cities only. With the help of “Skip(1)” Operator on Linq result I am skipping the First record in the list and then With the help of “Take(5)” I am taking only next 5 records from the resulted list.
The .NET Standard Query Operators are not hardcoded list so it can be added and replaced by the developers. This is the Example of Extension Methods provided by the .NET itself with the LINQ.
If you have read the Linq query carefully then you had notedown how I had sort the data in the query using the “orderby” and “descending” operator.
In the next Example I am showing you use of “Lambda Expression” with few more operators of .NET Standard Query Operators.
Code For HTML
<div>
<h1>Aggregate Value Samples</h1>

<div>
<b>Farthest Distance City:</b>
<asp:label id="MaxCityNameTxt" runat="server" text="Label"></asp:Label>
<asp:label id="MaxCityDistanceTxt" runat="server" text="Label"></asp:Label>
</div>

<div>
<b>Total Travel Distance (outside of US):</b>
<asp:label id="TotalDistanceTxt" runat="server" text="Label"></asp:Label>
</div>

<div>
<b>Average Distance:</b>
<asp:label id="AverageDistanceTxt" runat="server" text="Label"></asp:Label>
</div>

</div>


Code For .cs file
///calculate Farthest city away
Location farthestCity = (from location in travel.PlacesVisited
orderby location.Distance descending
select location).First();
MaxCityNameTxt.Text = farthestCity.city;
MaxCityDistanceTxt.Text = "(" + farthestCity.Distance + " miles)";

///calculate total city distances of all cities outside US
int totalDistance = (from location in travel.PlacesVisited
where location.Country != "USA"
select location).Sum(loc => loc.Distance);

TotalDistanceTxt.Text = totalDistance + " miles";

/// calculating average city distances of each city trip

double averageDistance = travel.PlacesVisited.Average(loc => loc.Distance);
AverageDistanceTxt.Text = averageDistance + " miles";

In the above Example In the First query I had use the “First()” operator which gives the only first record of the result set.
In the next query I had use the “Sum()” operator with the new feature of c# 3.0 “Lambda Expression”. The Lambda expression create the one instance of the object which currently in the from expression and then we can apply our calculation on top of that instance.
In the last query I had use the “Average()” operator again with the Lambda expression.
In the Second query I had also filter the data in the where condition for country not equal to “USA” we can also apply various string operation on that property of the instance to filter the data.
In the next exmaple we will explore the new feature of c# 3.0 “Anonymous Type” – This is allows you to easily create and use type structures inline without having to formally declare their object model instead it can be use by the initialization of the data.
Code of HTML

<div>
<b>Average Distance:</b>
<asp:label id="AverageDistanceTxt" runat="server" text="Label"></asp:Label>

</div>
Code of .cs
///Anonymous Type
grdAnonymousType1.DataSource = from location in travel.PlacesVisited
orderby location.city
select new
{ City = location.city, Distance = location.Distance };

grdAnonymousType1.DataBind();

Note that instead of returning a “location” from our select clause like before, I am instead creating a new anonymous type that has two properties – “City” and “Distance”. The types of these properties are automatically calculated based on the value of their initial assignment (in this case a string and an int).
In the next example we will see the critical operation of grouping of LINQ with the anonymous Type
Code for HTML

<div>
<h1>Groupings with Anonymous Classes</h1>

<asp:gridview id="grdAnonymousType2" autogeneratecolumns="false" runat="server">
<columns>

<asp:boundfield headertext="Country" datafield="Country">

<asp:templatefield headertext="Cities">
<itemtemplate>

<asp:BulletedList ID="BulletedList1" runat="server"
DataSource='<%#Eval("Cities")%>' DataValueField="City"/>

</itemtemplate>
</asp:TemplateField>

<asp:boundfield headertext="Total Distance" datafield="TotalDistance">

</columns>
</asp:GridView>
</div>

Code for .cs
grdAnonymousType2.DataSource = from location in travel.PlacesVisited
group location by location.Country into loc
select new
{
Country = loc.Key,
Cities = loc,
TotalDistance = loc.Sum(dist => dist.Distance)
};
grdAnonymousType2.DataBind();

The above sample provides a richer and more practical scenario. It transforms our list of cities into a hierarchical result collection – where we group the results around countries using an anonymous type that we define that contains the country name, a sub-collection list of city details, and the sum of the total distance of all cities within the country (computed using a lambda expression).

Comments

Popular posts from this blog

To Move items from one ListBox to another Listbox

Receive Json Web response in C#