Monday, 2 January 2017

Linq Where Filter Sample in various ways


In this post we  are going to see how to use the where Filter sample in Linq.



public abstract class Person
{
    public int ID { set; get; }

    public string Name { set; get; }

    public int PhoneNumber { set; get; }

    public string Address { set; get; }
}


public class Student:Person
{
    public string Department { set; get; }

    public int TotalMarks { set; get; }

}




        List<Student> StudentList = new List<Student>() {

            new Student(){ ID =4,
Name="Suresh",
Address="Porur",
TotalMarks=350,
Department="ECE",
PhoneNumber=12321312
},
            new Student(){ ID=2,
Name="Ramu",
Address="Delhi",
TotalMarks=450,
Department="CSE",
PhoneNumber=23233112
},
             new Student(){
ID=1,
Name="Rajesh",
Address="Madurai",
TotalMarks=400,
Department="ECE",
PhoneNumber=3434322
},
            new Student(){
ID=3,
Name="Rajesh",
Address="Chennai",
TotalMarks=460,
Department="CSE",
PhoneNumber=43434223
},
            new Student(){
ID=5,
Name="Hanish",
Address="Salem",
TotalMarks=420,
Department="EEE",
PhoneNumber=34423232
}

        };




        IEnumerable<Student> filteredStuds = StudentList.Where(x => x.ID > 2);
     
        foreach (var item in filteredStuds)
        {
            Console.WriteLine(string.Format("ID : {0}, Name {1}", item.ID, item.Name));
        }


Output:
*****************
ID : 4, Name Suresh
ID : 3, Name Rajesh 
ID : 5, Name Hanish





        var sqlFiltered = from x in StudentList
                          where x.ID > 2
                          select x;

        foreach (var item in sqlFiltered)
        {
            Console.WriteLine(string.Format("ID : {0}, Name {1}", item.ID, item.Name));
        }


       


Output:
*****************
ID : 4, Name Suresh
ID : 3, Name Rajesh 
ID : 5, Name Hanish



From this post you can learn how to use the where filter in Linq in lambda expression as well as in Linq To Sql format.

No comments:

Post a Comment