Monday 2 January 2017

Linq ofType method sample

In this post we  are going to see how we are using the OfType method in Linq, for that we are taking a example of three classes 



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 Employee : Person
{
    public string Designation { set; get; }

    public string Department { set; get; }

    public int CollegeStudentId { set; get; }
}

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

    public int TotalMarks { set; get; }

}



We are creating a generic list where we can add both types under one collection , but we are filtering that using the Typeof method for getting the student collection alone.



         
        List<Person> genericList = new List<Person>() {

              new Student() {      ID=2,
Name="Ramu",
Address="Delhi",
TotalMarks=450,
Department="CSE",
PhoneNumber=23233112
},
new Employee() {     ID = 103,
Name="Rajesh",
Department="Development",
Address="TN",
PhoneNumber=232323,
CollegeStudentId=1,
Designation="Architect"
},
            new Student(){
ID=5,
Name="Hanish",
Address="Salem",
TotalMarks=420,
Department="EEE",
PhoneNumber=3442323
},
            new Employee(){
ID = 101,
Name="Hanish",
Department="Development",
Address="US",
PhoneNumber=238564334,
CollegeStudentId=5,
Designation="TL"
},
            new Student(){
ID =4,
Name="Suresh",
Address="Porur",
TotalMarks=350,
Department="ECE",
PhoneNumber=12321312
}
        };



        IEnumerable<Student> studs = genericList.OfType<Student>();



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



        Console.Read();



Output:
********************

Name : Ramu, Marks 450
Name : Hanish, Marks 420
Name : Suresh, Marks 350

No comments:

Post a Comment