LINQ tip to use proper for loop

Dear Friends,

As a programmer I would like to share some of the best tips which I found so far and this is one of the tip which I am going to share right away

suppose you have following  piece of code

string[] Names= namecollection.Split(GetDelimeter());

           List<string> NameList = new List<string>();

foreach (string name in Names)
              if (!string.IsNullOrEmpty(name ))
                  sb.Append(name .Trim() + ",");
                  NameList .Add(name .Trim());

Now you can write above  for each code  & if condition in following way

foreach (string Nam in Names.Where(Nam=> !string.IsNullOrEmpty(Nam)))
               sb.Append(Nam .Trim() + ",");
             NameList .Add(Nam.Trim());

It is much faster then a earlier code which shown

Hope you like this. Enjoy  Reading


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

Book detail by ISBN number using ASP.NET

Dear Friends,
I am explaining basic steps by which you can get book detail from ISBN using ASP.NET

I am using 3 providers which have this database catalog and provide such facility.
So below is the list
3)    Google book API
So let us start with first. So to use this service you have to create first access key.

We can get access key by registration at and it is free.
Now when you have access key then you can play with the URL which is responsible for providing the book detail response as shown below

The response of the above URL is XML.
To achieve this I did have created a constant for above URL as shown below

Private Const ISBNAPIURL As String =””

Now on web page I have used a textbox for ISBN number and a button for search

So on click of button search event we did following code

If Me.txtISBN.Text <> String.Empty Then
Dim requestURL As String
Step1: created  request url at run time to fetch ISBN number
requestURL = ISBNAPIURL + Common.GetISBNConfig().ToString() + “&index1=isbn&value1=” + Me.txtISBN.Text.ToString()

‘step2: now as the return type is fixed XML format I have provided the response to XDocument
Dim xDoc As XDocument = XDocument.Load(requestURL)

‘Step 3:- On the avbove XDoc I have applied LINQ to XML and as we know the XML node will have following book elements so we have used it.

Dim resultSet = From book In xDoc.Descendants(“BookData”)
Select New BookDetail() With {.BookTitle = book.Element(“Title”).Value,
.BookAuthor = book.Element(“AuthorsText”).Value,
.BookPublisher = book.Element(“PublisherText”).Value}

Step4 : now we check whether the result set have something or not and  If we found  entry then we assign the output to project.

If resultSet Is Nothing = False AndAlso resultSet.Count() > 0 Then
Me.lblBookName.Text = resultSet.FirstOrDefault().BookTitle.ToString()
Me.lblAuthor.Text = resultSet.FirstOrDefault().BookAuthor.ToString()
Me.lblPublisher.Text = resultSet.FirstOrDefault().BookPublisher.ToString()
Me.lblMessage.Text = “Sorry ISBN Number not found, Please try different number.”
End If
Me.lblMessage.Text = “Please enter the ISBN number”
End If

In this way you can get book detail by ISBN using LINQ to XML feature.

In the next tutorial we  will use wordcat api to access book information using ASP.NET.

Thanks & Best Regards,

Rajat Jaiswal


A new milestone 125th post on so far so good

Dear Friends,
This post is different post from my regular technical articles and it is my 125th post on

I would like to thank all of my friends, family members, colleges & most valuable the reader of this blog who continuously giving feedback and improving my skill also.
So thank you very very much.
Keep reading, Keep commenting, and keep giving feedback.
I need more improvement and I know you people will help me in sharing my thoughts.
God bless you all.

Happy Holidays.

Merry Christmas.
Rajat Jaiswal

Project List on which we will work in future

Dear Friends,

 Merry Christmas!

I Hope you are enjoying  the holidays.

 After seeing the market trend and requirements I am interested in making following projects which will help me and other friends to understand basic project development and use latest technologies with some productive output.

 In coming up sessions i am going to use this project topic and create sample with latest technologies like Silverlight, Windows phone 7, VS 2010 etc.

 So here we go

 1) College Management

 2) School Management

3) Job Portal

 4) Forums

5) Blog

6) Employee Management

7) Bug Tracker

8) Time Sheet

9) Address Book

10) Project Management

11) Survey engine

 12) Stock Manager

13) Property Broker

14) Shop Management

15) Matrimonial

 16) Social Networking

17) Hotel Management

 18) Inventory Management

19) Accounting

20) Transport Management

21) Hospital Management

22) Ecommerce

Etc are the project list on which I will work in future to enhance my knowledge with productive work.

I will share code base and case study also in future

Hope you like it Once again wish you Merry Christmas.


 Rajat Jaiswal

Some useful Terminology (acronyms)

Hello friends,
Here I am with some useful terminology and these acronyms are generally used now days in broad way take a look.
1) ESB : Enterprise Service Bus
2) POX : Plain OLD XML
3) REST: Representational State Transfer
4) SOAP: Simple Object Access Protocol
5) RIA : Rich Internet Application
6) XML : Extensible Markup Language
7) JASON: Java Script Object Notation
8) DOM : Document Object Modeling
9) XAML : Extensible Application Markup Language
10) LINQ : Language Integrated Query
11) RSS: Really Simple Syndication
12) WCF: Windows Communication Foundation
13) WF: Windows Foundation
14) WPF: Windows Presentation Foundation
15) AJAX: Asynchronous Java script and XML
16) XLST: Extensible Style Sheet Language Transformation
17) INDIGO: Code name of Microsoft windows Communication foundation Technology
18) OSLO: Code name of Microsoft Modeling Technology
19) SOA: Service Oriented Architecture
20) ORCAS: dot net 3.5 Version called ORCAS
21) AVALON: code name of Microsoft Windows Presentation foundation Technology
22) Azure: Microsoft new Operation system Related to Cloud computing
23) Astoria : Code name of Data services

I hope you people like it.
Enjoy life with dot net.

Your host
Rajat Jaiswal

How to read Resource files in our code by LINQ to XML ?

Hello friends,

Sorry for such a late post. Currently I am busy in too many works so not getting enough time to talk with you.

Today I am posting an interesting work which is how to read a resource file in our code with the help of LINQ TO SQL.

I can say only one thing which is its simple and easy to use. Just copy paste below code and you will get what to want.

Before code I will explain you that resource file is just like xml which has attributes and value and that particular attributes is your key.


Now we need to fetch value for particular key for a file for this you have to write below code. Where bv_strFileName is your resource file name and bv_strKey is key for which you need value.

Public Shared Function pub_LangaugeValue(ByVal bv_strFile As String, ByVal bv_strKey As String) As String


Dim strValue As String = “”

Dim resxXML As New XDocument

resxXML = XDocument.Load(bv_strFile)

Dim a = From data In resxXML.Root.Descendants(“data”) _

Where data.Attribute(“name”).Value = bv_strKey _

Select New With {.resxA = data.Attribute(“name”).Value, .ResxValue = data.Element(“value”).Value}

If a.Count() > 0 Then

strValue = a.FirstOrDefault().ResxValue.ToString()


strValue = bv_strKey

End If

Return strValue

Catch ex As Exception

Throw ex

End Try

End Function ‘pub_LangaugeValue


Where bv_strFileName is full path name of our resource file and bv_strkey is the key for which we need to find the value.

Below is example how to use it our aspx.

Suppose we want to read LabelResource1.text value in Spanish whose file name is


Then we have to call the above function like below.


With the help of above code.

We can get key’s value from different resource file.



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