Start querying with LINQ

  • Two fundamental building blocks of LINQ are the concepts of “elements” and “sequences”

Sequence

  • A sequence can be thought of as a list of items, with each item in the list being an element. A sequence is an instance of a class that implements the IEnumerable<T> interface.
    • Example for sequence

    int[] fibonacci = {0, 1, 1, 2, 3, 5};

  • sequence could be a local sequence of in-memory objects or a remote sequence
  • In the case of remote data sources (for example SQL Server), these remote sequences also implement the IQueryable<T> interface    

 

  • Queries that run on local sequences are known as local queries or LINQ-to-objects queries

     

  • Return value of query can be sequence or scalar value

     

     

int[] fibonacci = { 0, 1, 1, 2, 3, 5 };
// Scalar return value
int numberOfElements = fibonacci.Count();

Console.WriteLine(“Count: {0}”, numberOfElements);

 

// Output sequence return value

IEnumerable<int> distinctNumbers = fibonacci.Distinct();

Console.WriteLine(“Elements in output sequence:”);

 

foreach (var number in distinctNumbers)

{

Console.WriteLine(number);

}

 

Deferred execution

This means that the query does not execute when it is created, but when it is used or enumerated.

 

int[] fibonacci = { 0, 1, 1, 2, 3, 5 };

 

// Construct the query

IEnumerable<int> numbersGreaterThanTwoQuery = fibonacci.Where(x => x > 2);

 

// At this point the query has been created but not executed

 

// Change the first element of the input sequence

fibonacci[0] = 99;

 

// Cause the query to be executed (enumerated)

foreach (var number in numbersGreaterThanTwoQuery)

{

Console.WriteLine(number);

//query is executed when it’s called

}

 

Result

99

3

5

 

Exceptional cases

  • operators such as Count will cause the query to be executed immediately, and not deferred
  • There are a number of conversion operators that also cause immediate query execution, such as ToList, ToArray, ToLookup, and ToDictionary.

 

Lambda expressions in query operators

fibonacci.Where(x => x > 2)

Here the lambda expression x => x > 2 will only return elements (ints in this case) that are greater than 2.

 

Local and interpreted queries

LINQ provides for two distinct architectures: local and interpreted.

Local queries operate on IEnumerable<T> sequences and are compiled into the resulting assembly at compile time. Local queries, as the name suggests, can be thought of as operating on sequences local to the machine on which the query is executing (for example, querying an in-memory list of objects).

Interpreted queries are interpreted at runtime and work on sequences that can come from a remote source such as an SQL Server database. Interpreted queries operate on IQueryable<T> sequences.

There are two styles of writing LINQ queries:

  • Fluent style (or fluent syntax)
  • Query expression style (or query syntax)
  1. Fluent Style (extension methods)

Fluent syntax makes use of the query operator extension methods as defined in the static System.Linq.Enumerable class

Query operators can be used singularly, or chained together to create more complex queries

  1. Query Expression

Query expressions offer a syntactical nicety on top of the fluent syntax.

SQL like querying

 

Example:

namespace ConsoleApp

{


class
Ingredient

{


public
string Name { get; set; }


public
int Calories { get; set; }

}

 


//Main Class


class
Program

{


static
void Main(string[] args)

{


Ingredient[] ingredients = {


new
Ingredient { Name = “Sugar”, Calories = 500 },


new
Ingredient { Name = “Egg”, Calories = 100 },


new
Ingredient { Name = “Milk”, Calories = 150 },


new
Ingredient { Name = “Flour”, Calories = 50 },


new
Ingredient { Name = “Butter”, Calories = 200 }

};

 


#region Fluent style LINQ

 


IEnumerable<string> highCalorieIngredientNames =

ingredients.Where(x => x.Calories >= 150)

    .OrderBy(x => x.Name)

    .Select(x => x.Name);


//Ingredient object is transformed to a simple string. This transformation is called projection

 


//”x => x.Name” is called lambda expressions

 


foreach (var ingredientName in highCalorieIngredientNames) {


Console.WriteLine(ingredientName);

}

 

#endregion

 


#region Query expression style LINQ

 


IEnumerable<string> lowCalorieIngredientNames = from y in ingredients


where y.Calories <= 150


orderby y.Name


select y.Name;

 


foreach (var lowIngredient in lowCalorieIngredientNames) {


Console.WriteLine(lowIngredient);

}

 


#endregion

 


Console.ReadKey();

}

}

}

Range variables

 

  • Additional from clauses
  • The let clause

It is sometimes useful to store the result of a sub-expression in order to use it in subsequent clauses

 


IEnumerable<Ingredient> highCalDairyQuery =


from i in ingredients


let isDairy = i.Name == “Milk” || i.Name == “Butter”


where i.Calories >= 150 && isDairy


select i;

// isDairy keeps temporary value stored

 

 


//let can also be used to introduce a subsequence


string[] csvRecipes = { “milk,sugar,eggs”,


“flour,BUTTER,eggs”,


“vanilla,ChEEsE,oats” };

 


var dairyQuery = from csvRecipe in csvRecipes


let csvingredients = csvRecipe.Split(‘,’)


from ingredient in csvingredients //multiple from clause


let uppercaseIngredient = ingredient.ToUpper()


where uppercaseIngredient == “MILK”

|| uppercaseIngredient == “BUTTER”

|| uppercaseIngredient == “CHEESE”


select uppercaseIngredient;

 


foreach (var dairyIngredient in dairyQuery) {


Console.WriteLine(“{0} is dairy”, dairyIngredient);

}

 

  • The into keyword

To be declared that can store the result of a select clause (as well as group and join clauses)


IEnumerable<Ingredient> highCalDairyQuery =


from i in ingredients


select
new
// anonymous type

{

OriginalIngredient = i,

IsDairy = i.Name == “Milk” || i.Name == “Butter”,

IsHighCalorie = i.Calories >= 150

}


into temp


where temp.IsDairy && temp.IsHighCalorie


// cannot write “select i;” as into hides the previous range variable i


select temp.OriginalIngredient;

  • The join clause

The join clause takes two input sequences in which elements in either sequence do not necessarily have any direct relationship in the class domain model.

Common types of joins include:

 Inner joins.

 Group joins.

 Left outer joins.

Inner Join

//INNER JOIN


Recipe[] recipes = {


new
Recipe { Id = 1, Name = “Mashed Potato” },


new
Recipe { Id = 2, Name = “Crispy Duck” },


new
Recipe { Id = 3, Name = “Sachertorte” }};

 


Review[] reviews = {


new
Review { RecipeId = 1, ReviewText = “Tasty!” },


new
Review { RecipeId = 1, ReviewText = “Not nice :(“ },


new
Review { RecipeId = 1, ReviewText = “Pretty good” },


new
Review { RecipeId = 2, ReviewText = “Too hard” },


new
Review { RecipeId = 2, ReviewText = “Loved it” }

};

 


var query = from recipe in recipes


join review in reviews


on recipe.Id equals review.RecipeId


select
new
// anonymous type

{

RecipeName = recipe.Name,

RecipeReview = review.ReviewText

};

 


foreach (var item in query) {


Console.WriteLine(“{0} – ‘{1}'”, item.RecipeName, item.RecipeReview);

}

Group join

//group join


var query = from recipe in recipes


join review in reviews


on recipe.Id equals review.RecipeId


into reviewGroup


select
new
// anonymous type

{

RecipeName = recipe.Name,

Reviews = reviewGroup // collection of related reviews

};

 


foreach (var item in query) {


Console.WriteLine(“Reviews for {0}”, item.RecipeName);

 


foreach (var review in item.Reviews) {


Console.WriteLine(” – {0}”, review.ReviewText);

}

}

    

 


 


Generics Example in C#

using System;

namespace Generics
{

public class MyGeneric<T>
{   //type of the class is ommited
private T[] array;
public MyGeneric(int size)
{
array = new T[size + 1];
}
public T getItem(int index)
{
return array[index];
}
public void setItem(int index, T value)
{
array[index] = value;
}
}
class Program
{
static void Main(string[] args)
{
//declare double array
MyGeneric<double> doubleArray = new MyGeneric<double>(5);

//set values
double x;
for (int c = 0; c < 5; c++)
{
x = c * 10;
doubleArray.setItem(c, Convert.ToDouble(x));
}

//get values
for (int a = 0; a < 5; a++)
{
Console.WriteLine(doubleArray.getItem(a));
}

Console.ReadLine();
}

}
}

Equals in Object Class (Comparing objects)

using System;

namespace Object_Class_ToString
{
class Emp
{
int id;
string name;

public int Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
//public override string ToString()
//{
//    return string.Format(“{0} – {1}”, id,name);
//}
}

class Program
{
static void Main(string[] args)
{
Emp e1 = new Emp();
Emp e2 = e1;
Console.WriteLine(e1.Equals(e2));
//will return true since both refering to same object

Emp e3 = new Emp();//new Object
e2 = e3;
Console.WriteLine(e1.Equals(e2));
//will return false they are refering to different objects
Console.ReadLine();
}
}
}

Delegates in C#

  • comes under System.delegates
  • type of variable which keeps references to methods
  • defines return type and parameter list

Example:

class Program
{
//declaring delegate
delegate double calc(num1,num2);

public double addition(num1,num2)//same signature
{return num1+num2;}

public double minus(num1,num2)//same signature
{return num1-num2;}
}

class MainClass
{
private static void main(string[] args)
{
calc delObj;//created object with delegate
string input=Console.readLine();
if(input==’Add’)
{
//instantiate delegate with reference to addition
delObj=new delObj(addition);
}
else
{
//instantiate delegate
delObj=new delObj(minus);
}

//call delegate
delObj(10,20)
}
}

Stored procedures sample program

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace Stored_Proc
{
public partial class WebForm1 : System.Web.UI.Page
{

//DataSet ds = new DataSet();

SqlConnection con;

SqlCommand cmd = new SqlCommand();

//SqlParameter sp1 = new SqlParameter();
//SqlParameter sp2 = new SqlParameter();
//SqlParameter sp3 = new SqlParameter();
//SqlParameter sp4 = new SqlParameter();

protected void Page_Load(object sender, EventArgs e)
{
Label6.Text = null;

doSomething();
}

protected void Button1_Click(object sender, EventArgs e)
{
con = new SqlConnection(“Data Source=KUSHANLAHIRU-PC;Initial Catalog=example1;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False”);
cmd = new SqlCommand(“Splogin”, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(“@ID”, SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add(“@Password”, SqlDbType.VarChar).Value = TextBox2.Text;
cmd.Parameters.Add(“@ConfirmPassword”, SqlDbType.VarChar).Value = TextBox3.Text;
cmd.Parameters.Add(“@EmailID”, SqlDbType.VarChar).Value = TextBox4.Text;

con.Open();
cmd.ExecuteNonQuery();
Label5.Text = “Successful”;

con.Close();
}

private void doSomething()
{
string str = null;
string retString = null;
str = “This is substring test”;
retString = str.Substring(8, 9);
//MessageBox.Show(retString);
Label6.Text = retString.ToString();
}

}
}

GOOGLE MAPS API sample program

SAMPLE CLASS TO GET DISTANCE BETWEEN TWO GEO PLACES AND AND RETRIEVE OTHER DETAILS by USING GOOGLE MAPS API

/*just uploaded without explanations ,if someone needs more contact me*/

 

using System.IO;
using System.Net;
using System.Xml;

/*
* author : @kushanlahiru
*
*
how to use the class
*
*first setValues(string destination, string origin)
*second calculateDistance()
*third get values distance or travel details
*/
namespace Data
{
public class GoogleDistance
{

private string destination;

private string origin;

private string distance;

private string travelDetail;
GoogleDistance() //constructor
{
destination=””;
origin=””;
distance=””;
travelDetail=””;
}
public string getTravelDetail()
{
return travelDetail;
}

 

public string getDistance()
{
return distance;
}

 

public void setValues(string destination, string origin)
{
this.destination = destination;
this.origin = origin;
}

 

public void calculateDistance()
{

string xmlResult = null;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(“http://maps.googleapis.com/maps/api/distancematrix/xml?origins=&#8221;
+ origin + “&destinations=” + destination + “&mode=Car&language=us-en&sensor=false”);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader resStream = new StreamReader(response.GetResponseStream());
XmlDocument doc = new XmlDocument();
xmlResult = resStream.ReadToEnd();
doc.LoadXml(xmlResult);

string output = “”;

try
{
if (doc.DocumentElement.SelectSingleNode(“/DistanceMatrixResponse/row/element/status”).InnerText.ToString().ToUpper() != “OK”)
{
travelDetail = “Invalid City Name please or entries, try again”;
return;
}
XmlNodeList xnList = doc.SelectNodes(“/DistanceMatrixResponse”);
foreach (XmlNode xn in xnList)
{
if (xn[“status”].InnerText.ToString() == “OK”)
{
output = “<table align=’center’ width=’600′ cellpadding=’0′ cellspacing=’0′>”;
output += “<tr><td height=’60’ colspan=’2′ align=’center’><b>Travel Details</b></td>”;
output += “<tr><td height=’40’ width=’30%’ align=’left’>Orgin Place</td><td align=’left’>” + xn[“origin_address”].InnerText.ToString() + “</td></tr>”;
output += “<tr><td height=’40’ align=’left’>Destination Place</td><td align=’left’>” + xn[“destination_address”].InnerText.ToString() + “</td></tr>”;
output += “<tr><td height=’40’ align=’left’>Travel Duration (apprx.)</td><td align=’left’>” + doc.DocumentElement.SelectSingleNode(“/DistanceMatrixResponse/row/element/duration/text”).InnerText + “</td></tr>”;
output += “<tr><td height=’40’ align=’left’>Distance</td><td align=’left’>” + doc.DocumentElement.SelectSingleNode(“/DistanceMatrixResponse/row/element/distance/text”).InnerText + “</td></tr>”;
output += “</table>”;

travelDetail = output;

distance = doc.DocumentElement.SelectSingleNode(“/DistanceMatrixResponse/row/element/distance/text”).InnerText;
}
}
}
//catch (Exception ex)
//{

// return;
//}
finally
{

}
}//end of get distance method
}
}

 

Simplest way to send email from your C# (ASP.net) application

<1> IMPORT LIBRARIES >> TO FORM(or ASPX page ) & CLASS 

using System.Net.Mail;

<2>INCLUDE CLASS BELOW 

class sendmail
{
public void testmail(string to,string subject,string body)
{
try
{
string To=to;
string sub=subject ;
string Body=body ;
MailMessage mail = new MailMessage();

SmtpClient SmtpServer = new SmtpClient(“smtp.gmail.com”);

mail.From = new MailAddress(“absccd@gmail.com”);

// email adress that i have created on gmail

// or you can use any mail server such as yahoo,aol,msn,and so on

mail.To.Add(To);

mail.Subject = sub;

mail.Body = Body;

SmtpServer.Port = 587;

SmtpServer.Credentials = new System.Net.NetworkCredential(“userNAme”, “Password”);

//enter uname and pwd of email address you want to send email from

SmtpServer.EnableSsl = true;

SmtpServer.Send(mail);

MessageBox.Show(“mail Sent successfully”);

}

catch (Exception ex)
{

MessageBox.Show(ex.ToString());

}

}

}

<3>CREATE OBJECTS FROM THAT(in the form or page) and USE IT

sendmail obj = new sendmail();
obj.testmail(toContentTextBox.Text, subjectContentTextBox.Text, messageContentTextBox.Text);

 

//enjoy your program