Free Web Development Online Tutorials, Learn to Code
Query Syntax in LINQ with C#, Language Integrated query with different Data Source

LINQ Query Syntax Example

In this tutorial we learn about LINQ query syntax using C#.

Query Syntax in LINQ with C#

In earlier tutorials we have already discussed about method syntax and lambda expression in LINQ,

Here we have created a student list, so we can use the list object in example below.

var studentsStream = new List<Student> { 
    new Student { FullName = "Aruna", StreamId=1,  Score = 10 },
    new Student { FullName = "Janet", StreamId=2,  Score = 9  },
    new Student { FullName = "Ajay", StreamId=1,  Score = 11 },
    new Student { FullName = "Kunal", StreamId=2,  Score = 13  },
    new Student { FullName = "Chandra", StreamId=2,  Score = 8  },

c# query syntax select one column

Example 1: from above student list we want to select only student names

//  (Query syntax)
var studentNames = from s in studentsStream
select s.FullName; 

c# query syntax select where in list

Example 2: from above student list select students where score is more than 10

// Query syntax with where claues 
var studentList = from stu in studentsStream where stu.Score>10 select stu;

linq query syntax join

Before you learn how to write join in query syntax, I recommend you to go through the post about different type of Joins in LINQ.

Here is example you will learn how to write join among multiple list objects, like Order list, Customer list, Product list.

LINQ INNER JOIN example : Below is an example of joining multiple tables in linq, notice we have joined based on two columns, customer id and product id, after joining the result set is stored into variable which is anonymous type.

var OrderList = GetOrderList();
var CustomerList = GetCustomerList();
var ProductList = GetProductList();
var q1 = (from order in OrderList join cust in CustomerList on order.CustomerId equals cust.CustomerId join p in ProductList on  order.ItemId equals p.ProductId
            orderby cust.CustomerId
            select new

After joining multiple tables we are storing the result set into a Anonymous type variable.

Read from anonymous type

Now we have to read values from anonymous type, this is how you can extract values from that variable.

foreach (var item in q1)
    Console.WriteLine(string.Format("{0} - {1} - {2}", item.ProductName, item.Price, item.CustomerName));
Learn LINQ .Net

Query Syntax LINQ

linq Interview Questions Answers

LINQ C# examples | Join MVC Course