LINQ Queries with Answer

In this tutorial I am discussing some linq queries with answer. In this artical i will discuss linq queries based on sql, object and xml.

LINQ to SQL Basic Queries

Following is the table schema which i am using for linq to sql basic queries:-

Table Name:- Employee


[Table]
public class Employee
{
    [Column(Name ="emp_id",IsPrimaryKey =true,IsDbGenerated =true)]
    public int ID { get; set; }
    [Column(Name = "emp_name")]
    public string name { get; set; }
    [Column(Name = "emp_age")]
    public int? age { get; set; }
    [Column(Name = "emp_email")]
    public string emailid { get; set; }
    [Column(Name = "emp_gender")]
    public char gender { get; set; }
    [Column(Name = "emp_salary")]
    public Int64? salary { get; set; }
}
		

Create the object of DataContext class


DataContext dc = new DataContext("Data Source =.; Initial Catalog = myfirstdatabase; Integrated Security = True");
		

1.   Select data of all candidates whose age is greater than 25


var q1 = dc.GetTable<Employee>().Where(x => x.age > 25);
		

2.   Select data of all female candidates


var q2 = dc.GetTable<Employee>.Where(x => x.gender == 'F');
		

3.   Select all data whose age between 25 to 30


var q3 = dc.GetTable<Employee>().Where(x => x.age > 25 & & x.age < 30);
		

4.   Select all records of female candidates whose emp id is between 103 to 106


var q4 = dc.GetTable<Employee>().Where(x => x.ID >= 103 && x.ID <= 106 && x.gender == 'F');
		

5.   Select the data of candidates whose name is isha Malhotra


var q5 = dc.GetTable<Employee>().Where(x => x.name == "isha malhotra");
		


6.  Select the data of candidates whose age is 30


var q6 = dc.GetTable<Employee>().Where(x => x.age == 30);
		

7.  Select the data of candidates whose name start with ‘r’


var q7 = dc.GetTable<Employee>().Where(x => x.name.StartsWith("r"));
		

8.  Select the data of candidates who is having gmail email id.


var q8 = dc.GetTable<Employee>().Where(x => x.emailid.Contains("gmail"));
		

9.  Select the data of candidates whose last name is arora


var q9 = dc.GetTable<Employee>().Where(x => x.name.EndsWith("arora"));
		

10.  Select the data of candidates whose name contains sh.


var q10 = dc.GetTable<Employee>().Where(x => x.name.Contains("sh"));
		

11.  Select the data of candidates whose age is either 20,30 or 35


var q11 = dc.GetTable<Employee>().Where(x => x.age == 20 || x.age == 30 || x.age == 35);