Can you explain how a basic LINQ Query looks like?

 Posted by ArticlesMaint on 9/29/2009 | Category: LINQ Interview questions | Views: 4124

In order to understand the basic query for LINQ, let’s make a small sample project. Let’s take customer data which has customer and orders.

Customer Name Customer Code City Orders
Khadak 001 Mumbai

  • Shirts

  • Socks
Shiv 002 Delhi

  • Pants
Raju 003 Mumbai

  • Socks
Shaam 004 Delhi

  • Shoes

We have made the data a bit complex by have one customer and multiple orders , in other words we have one as to many relationship.

So let’s make two classes one is the customer class aggregated with a collection of addresses class. Below is how the class structure will look like to accommodate the one as to many relationships of customer and multiple addresses.

The multiple addresses are the array collection aggregated inside the customer class. So below is the code snippet which is loading the customer and address collections with hard coded data provided in the above table. Currently its hardcoded but this can be loaded from database or some other source also.

clsCustomer[] objCustomer = new clsCustomer[]

new clsCustomer{CustomerName="Khadak",customerCode="001",City="Mumbai",Orders = new clsOrder[]
{new clsOrder{ProductName="Shirt"},
new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shiv",customerCode="002",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Pants"}}},
new clsCustomer{CustomerName="Raju",customerCode="003",City="Mumbai",Orders = new clsOrder[]{new clsOrder{ProductName="Socks"}}},
new clsCustomer{CustomerName="Shaam",customerCode="004",City="Delhi",Orders = new clsOrder[]{new clsOrder{ProductName="Shoes"}}}};

A basic LINQ query looks like something as shown below. Its start with the verb from followed by the data type and object i.e. ‘clsCustomer’ and ‘obj’ object. ‘objCustomer’ is the collection which has customer and addresses which we have loaded in the top section. ‘select obj’ specifies that we need all the values.

from clsCustomer obj in objCustomer select obj

Below figure shows in the right hand side the query in LINQ. In the left hand side we loop through the object collection.


We have made a simple project which demonstrates the basic LINQ query; you can download the same see how it works actually. Below figure shows the execution of the simple query.

Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Login to post response