LINQ with CheckBox List–LINQ Tips

Dear All,

There are many situation where you need to comma separated values of all the checked items of a checkbox list for this situation you generally write following  code

string allowedProductfamilies = string.Empty;
foreach (ListItem lItem in chkFamily.Items)
                    if (lItem.Selected)
                        allowedProductfamilies += lItem.Value + ",";

Now the above code is fine but can be improve more with following lines of code you can directly replace above lines with following lines of the code

string allowedProductfamilies = string.Empty;

allowedProductfamilies = chkFamily.Items.Cast<ListItem>().Where(lItem => lItem.Selected).Aggregate(allowedProductfamilies, (current, lItem) => current + (lItem.Value + ","));


I am sure you like the code.

Enjoy .Net , Enjoy LINQ .

Your Friend,

Rajat Jaiswal

How to get distinct entities from a collection using LINQ ?

Dear All,
Many times you have problems like you have a collection which has duplicate entries now you want a LINQ operation which provides you distinct collection as result.
Let start with following example
I have one class which is Contact as declared follow

public class Contacts        {
public string FirstName { get; set; }
public string LastName { get; set; }
public string Phone { get; set; }

This class has FirstName, LastName & mobile property.
Now suppose you have following collection

List<Contacts> oContacts = new List<Contacts>() {
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Sparsh", LastName="Anchaliya", Phone="223"},
new Contacts{ FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{ FirstName ="Arjun", LastName="Singh", Phone="523"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Sparsh", LastName="Anchaliya", Phone="223"},
new Contacts{ FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{FirstName ="Ajit", LastName="Bagora", Phone="423"},
new Contacts{ FirstName ="Rajat", LastName="Jaiswal", Phone="123"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Piyush", LastName="Redwal", Phone="623"},
new Contacts{ FirstName ="Arjun", LastName="Singh", Phone="523"},

Now the above collection having total 13 contact entities but there is only 5 records which are distinct.
Now you want a LINQ operation which provides only 5 records which are distinct.
To get this we will write following LINQ

List<Contacts> lstContact = oContacts.GroupBy(x => x.FirstName + x.LastName + x.Phone).Select(y => y.First()).ToList<Contacts>() ;

The above LINQ operation will provide you distinct entities.
The logic behind the above statement is very simple we just group by all the columns first and selected first records from that group collection for each group.

I hope you also enjoyed with above LINQ operation as I enjoyed.

Keep Learning
Rajat Jaiswal

LINQ tutorial Part -VI

Validation in Linq (Business Logic) :-

As a programmer my first intention is to make a bug free code for that one of the part is data validation.What ever we want to insert /Update in database need to check.

For this we use data validation. With linq we can refine data in mainly two way. The first and basic way in which we do not have to do so much is Schema.

What ever OR mapping is done. The schema handle the database type which require to save in database. By this a user can not insert invalid datatype in DataBase.

Second and another important aspect is using validation rules or custom validation. This can be handle in two way

1) custom property validation support.

This can be understand by below example suppose I want to insert email address in database with proper email format. But if there is no validation for format check then user can insert and data in email field for this purpose we require cutome property validation.

As the class genrated with LINQ to sql is partial class so we can use it any where we want with just partial class use.

Imports system

Imports system.text.RegularExpression

Partial Class Customer

Private Sub OnstrEmailChanging(ByVal value As String)

Dim regMailEx As New System.Text.RegularExpressions.Regex(“^([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*@([0-9a-zA-Z][-\w]*[0-9a-zA-Z]\.)+[a-zA-Z]{2,9})$”)

Dim matchExp As System.Text.RegularExpressions.Match

matchExp = regMailEx.Match(value)

If matchExp.Success =false Then

Throw new applicationException (“e-mail is not valid!”)

end if

End Sub

End class

In the above way we can validate a entry. Main benefit of this we do not have to write on each page and call validation. Its works automatically when user changed the Email.

Another is custom entry object validation.

In this suppose you want to compare two or more than two different object or some other logic then we can use this it can be handle is partial class with onValidate method.

As shown below.

Private Sub OnValidate(ByVal action As System.Data.Linq.ChangeAction)If action = Data.Linq.ChangeAction.Insert OrElse action = Data.Linq.ChangeAction.Update Then

if Me.blnActive = true AndAlso Me.datActiveDate is nothing then

Throw New applicationException (“Activation date is required!”)

End if

End If

End Sub

in this way we can use validation.

So enjoy coding.



LINQ tutorial Part -V

store procedures output variable & Functions work with LINQ:-


Hello Friends,

Today we will discuss how to handle the function and procedure that have output variable or the procedure that having scalar value.

For that just create a dbml file same as we talked in our privious discussion. On the Method panel just drop all the function and procedures.

Let start with a function

Suppose we have a function in sql which gives us out put in Upper case which is as below.


 if exists (select * from dbo.sysobjects so where id = object_id(N‘[dbo].[fn_MakeUpper]’) and so.xtype = ‘FN’)

drop function [dbo].[fn_MakeUpper]

CREATE FUNCTION fn_MakeUpper(@strInput AS VARCHAR(50))











Now drop this function on Method Panel of dbml. This function can we be use as below

Dim db as new MyDataBaseContext()

Dim lnq = from c in db.customers SELECT new with {.name= db.fn_MakeUpper(c.strFirstName)}

In the above manner we can use function.

Now we are taking example of output parameter parameter with store procedures suppose we have a output parameter in store procedure that will return total no of rows then.

We do that in following manner.

@intTotalRecord AS int OUTPUT















SELECT @intTotalRecord= COUNT(*) FROM tblProductGo 

1. drop the store procedure in method panel of database context dbml.

Now you will get method proc_tblProductReadWithCount(byref intTotalRecord As integer?)

To use this you have to declare a nullable integer first which is as follows.

Dim intA as integer ?

The “?” mark represet here that the variable can be nullable.


db As New BillMasterDataContext

Dim intA As Integer?
Dim lnq = From c In db.Proc_tblProductReadWithCount(intA) Select
cMe.lblText.Text = intA.Tostring()

In this way we can use output variable.

I hope you understand what I want to say

I will upload bunch of code related to article on in forth coming weeks.

Once again Thanks from

 your host

Rajat Jaiswal

Keep coding and share Knowledge

LINQ tutorial Part -IV

. Linq To XML (Add ,edit ,delete ): –


One of the intresting topic is xml. As a programmer I am not using XML in my daily use but I like XML.

Today I just wondering to take a suitable example which will do add,edit & delete with LINQ. So first we have to Create a xml file for that lets we created a xml file with following format.

<?xml version=1.0 encoding=utf-8?>
<Person>RAJAT JAISWAL</Person>
Now if we want to add new record in this xml file then our first moto is to read the xml using linq . For this we first use a import statement

Imports System.Xml.Linq by this we are able to use Linq over xml.

Now for reading we just do same as we do for database read (linq to sql ) but before that we have to create the object of xdocument from where the data will be fatch. As shown below

Dim TrainXDoc As XDocument = XDocument.Load(Server.MapPath(“MyTraining.xml”))

What this statement does it create same object like dataContext in sql.

And below is linq over this document and the Descendants(“Training”) like table or other object like storeprocedure in dbContext.

Dim lnqTraining = From myTraining In TrainXDoc.Descendants(“Training”) _

Select New With {.Id = myTraining.Element(“Id”).Value, _

.Person = myTraining.Element(“Person”).Value, _

.FrameWork = myTraining.Element(“FrameWork”).Value, _

.ASPNET = myTraining.Element(“ASPNET”).Value, _

.SqlServer = myTraining.Element(“SqlServer”).Value, _

.LogicBuilding = myTraining.Element(“LogicBuilding”).Value, _

.HTML = myTraining.Element(“HTML”).Value, _

.Communication = myTraining.Element(“Communication”).Value, _

.Remark = myTraining.Element(“Remark”).Value}

In the above elements like a row in datatable and we access there column using the tag name like Id, Person,Framework.

Now our second moto is to Add & Update the Add a new record can be done as follows

TrainXDoc .Element(“Trainings”).Add(New XElement(“Training”, New XElement(“Id”, lngId), New XElement(“Person”, Me.txtName.Text.Trim), _

New XElement(“FrameWork”, ddlFramWork.SelectedValue), New XElement(“ASPNET”, ddlAspNet.SelectedValue), _

New XElement(“Communication”, ddlCommunication.SelectedValue), New XElement(“HTML”, Me.ddlHtml.SelectedValue), _

New XElement(“LogicBuilding”, Me.ddlLogicBuilding.SelectedValue), New XElement(“SqlServer”, Me.ddlSqlServer.SelectedValue), _

New XElement(“Remark”, Me.txtRemark.Text.Trim)))

Here it added new record in traindoc’s trainings element which was root element.

After this we use MyTrainXDoc.Save(Server.MapPath(“MyTraining.xml”)) which save in the file.

For update we just find the node using the linq which we want to update then made changes in the particular node elements. And call save method as above.

For delete just find the element from linq then remove like xRoot.Remove() then save the xdoc.

For more detail just download the code from

Thanks & Regards

Rajat Jaiswal

LINQ tutorial Part -III

Save,Update, delete & read by Store procedures In Linq
 Dear Friends,
Yesterday we take example of how to use linq for insert ,update & delete. But as a programmer you have question like how to handle store procedures for insert update & Delete.
So here I am with this topic.
Today we will look how to update a table data using same linq but with store procedures.
When you see yesterday example’s mydb.dbml file.

You find that there is two panel(if you are not able to see then right click on orm designer screen and select show method panel).

One where you drag table and the another which is blank so here we use that another panel.

That panel is called method panel you can drop store procedures and function over there as shown in below fig- 1









After getting procedures & function on method panel you have to do just a simple task.

Just assign the insert ,update & delete method to related table using the custom property and map the fields of store procedure.

For that just check the property of table as shown in fig -2


Then click on either insert ,update or delete you will get following screen. Fig-3


Just map according to your spname.
And rest the code will be same as we did earlier yesterday. So enjoy coding.





LINQ tutorial Part -II

4. Save , Update, Delete by LINQ :-  (Attached document :- linq-images )



Hello friends first of all happy new year to all of you. Today we will work on how to Save ,Update & delete record from database using linq.

For using this you have to work on Linq To sql class Object which you can find when you add new item . Its extension is “DBML”.

When you create object of this then it will add datacontext in end.

Suppose you given name mydb.dbml then its object will be “mydbDataContext”.

You will be find this in attach document (Pic -1). Its basically a ORM (object Relational mapper) just drop the table from database. You will find the relation structure as like in (pic -2) in document.

The drop table is now work as individual class and & the fields of the table work as property of class.

Suppose if you drop table Customer then it will work as customer class and fields are work as property of customer class.

Now suppose you want to add new customer in customer table in database.

Then you have to create a object of customer class like below

Dim dc as new MyDbDataContext (its object of your added dbml)

Dim obj as new customer

Obj.strFirstName = “RAJAT”

Obj.strLastName = “JAISWAL”



The above code add the data in database.

Now suppose you want to edit the same record from database then you have to write following code

Dim dc as new myDbDataContext

Dim lnq = (from a in dc.customer where lngId = 1).singleOrDefault()

Lnq.strFirstName =”RAJAT”

Lnq.strLastName =”JAI”


In that way you can update the customer record.

Now suppouse you want to delete record from database. Then you have to write following code.

Dim dc as new mydbDataContext()

Dim lnq = (from a in dc.customer where lngId = 1) .singleOrDefault()



In this way we can add edit, delete record.

In next topic we will how to add,edit,delete done by store procedure.

Enjoy Programming




LINQ tutorial Part -Ist

1. What is Linq ?

Ans :- LINQ is stands for Language Integrated Query.Its new set of technologies which provide simple statement like sql. On any object.

This just like simple Sql statements. Linq can be operational on Object, SQL and XML.

LINQ TO Object :- Linq to object allow you to query on collection of objects like array

LINQ To Sql :- by the name its clear that it will work on Data.With help on ORM we can use data to manipulate and access the data.

LINQ To XML :-One of the most important feature of linq is that it can be operational on XML too. With the help of this we can use XML in easy way for read & Write Operation.

2. Linq Operations :-

Linq is such utility which can be used by programmer in very easy way. There are many operation which we can use like select data, conditional selection, sum, average other operation can be perform on object with linq. All be below operation is applied on Sql & XML also.

Here I am with a array on which we do linq operation

Dim ah As Integer() = {10, 4, 6, 20, 55, 22, 1, 40, 66, 69, 77, 24, 20, 10, 33}

1) Simple Select :- it will return all the element of array

Ex:- dim lnq = from a in ah select a

2) Where clause :- The where clause work in below manner


Dim lnq = From a In ah Where a < 20 Order By a

With this we can find array element which is less then 20

Dim lnq = From a In ah Where a Mod 2 = 0 Order By a

with this statement we get element only which is fully divisible by 2

Dim lnq = From a In ah Where a = 66

With this we get only value 66

3) And clause :-

Ex:- Dim lnq = From a In ah Where a >= 30 And a <= 69 Order By a

with this we can get only those element which is in the range of 30 & 69

4) Or clause :-

Ex- Dim lnq = From a In ah Where a >= 30 Or a Mod 2 = 0 Order By a

With this we can get element in or condition means either element may be greater than 30 or modules with 2 will be 0.

5) Take clause :- take (number) with this we can get particular number of element from array which we specify


Dim lnq = From a In ah Select a Take 3 Order By a Descending

With this element we can get starting 3 element in array

6)Take With while condition :-

This is same the take clause means it also get selected element but only one thing is here up to which condition is true


Dim lnq = From a In ah Take While a Mod 2 = 0

This will take all the starting element from array whose modules 2 is zero if it breaks after 2 element then take statement terminate.

7) Skip:- It is just opposit to take it . It skip the number of elements from starting position as assign.


Dim lnq = From a In ah Skip 3

This will skip first 3 element from array

8) Skip with While:- It Will skip the element up to true condition

Ex:- Dim lnq = From a In ah Skip While a Mod 2 = 0

This will skip all the starting element from array whose modules 2 is zero.

9) Order by:- if we want to order by the linq then we can do this by order by. By default its ascending which can be change by writing descending after oder by if we want to oder by on second criteria using ThenBy we can use.


10) Reverse clause:- Reverse It reverse the selected records from linq


Dim lnq = (From a In ah Select a).Reverse()

it give us revese array elements

11) Distinct clause :-

Distinct operation give us distict element from linq.

Ex:- Dim lnq = From a In ah Select a Distinct

This will give distict element from array.

12) First clause :-First Clause give you first element of the linq.
Ex:-Dim lnq = (From a In ah Select a).First()
it Will give first element of the array.
13) Last clause :-

Its just opposite to first clause it will give last element of the linq.

Ex:-Dim lnq = (From a In ah Select a).Last()
it will give the last element of the array.

14) FirstOrDefault :-

if there is no value in selection then it will return the default value other wise it will return first Element.


Dim lnq = (From a In ah Select a).FirstOrDefault()

it Will give first element of the array.

15) LastOrDefault :-

if there is no value in selection then it will return the default value otherewise it will return the last element.


Dim lnq = (From a In ah Select a).LastOrDefault()

it Will give Last element of the array and if array don’t have any value then it will return zero.

16) ElementAt Clause :-

Element At particular index position & elementAtDeafult(position)


Dim lnq = (From a In ah Select a).ElementAt(16)

it will return element at index position 16

17) Count :-

It will give the number of element selected by linq.

Ex:-Dim lnq = (From a In ah Select a).Count()
18)Sum :- It will give sum of linq element.
Ex:-Dim lnq = (From a In ah Select a).Sum() 
19) Min:- It will return minimum from linq.
Ex:-Dim lnq = (From a In ah Select a).Min()
20) Max:-It will return from max from linq
Ex:-Dim lnq = (From a In ah Select a).Max()
21) Average :- it will give the average from linq .
Ex:-Dim lnq = (From a In ah Select a).Average()
Rest will be in next post.