Customizing LINQ’s ‘select’ statement - Part 8

This is eighth part of the ‘LINQ’ series posts that I have started from here. In the last post we explored how to join data from multiple data sources using ‘concat’ key. Now, in this post you will learn how to customize the LINQ’s ‘select’ statement to select subset of each Source Element.



Assuming following as data source:

Student.cs

    class Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Address { get; set; }
        public List<int> Marks { get; set; }
    }

Program.cs

List<Student> students = new List<Student>()
{
    new Student { ID=1, Name="Abhimanyu K Vatsa", Address="Bokaro", Marks= new List<int> {97, 92, 81, 90}},
    new Student { ID=2, Name="Deepak Kumar", Address="Dhanbad", Marks= new List<int> {70, 56, 87, 69}},
    new Student { ID=3, Name="Mohit Kumar", Address="Dhanbad", Marks= new List<int> {78, 76, 81, 56}},
    new Student { ID=4, Name="Geeta K", Address="Bokaro", Marks= new List<int> {95, 81, 54, 67}}
};

Study 1

Now, if you want to select only name of student’s then use following LINQ query:

var query = from student in students
            select student.Name;

foreach (var e in query)
{
    Console.WriteLine(e);
}

Output:

Abhimanyu K Vatsa
Deepak Kumar
Mohit Kumar
Geeta K

Study 2

Now, if you want to select name and address of the student then use following LINQ query:

var query = from student in students
            select new { Name = student.Name, Address = student.Address};

foreach (var e in query)
{
    Console.WriteLine(e.Name + " from " + e.Address);
}

Output:

Abhimanyu K Vatsa from Bokaro
Deepak Kumar from Dhanbad
Mohit Kumar from Dhanbad
Geeta K from Bokaro

Study 3

Now, if you want to select name, marks and even want to add it then use following query:

var query = from student in students
            select new { Name = student.Name, Mark = student.Marks};

int sum = 0;
foreach (var e in query)
{
    Console.Write(e.Name + " : ");
               
    foreach (var m in e.Mark)
    {
        sum = sum + m;
        Console.Write(m + " ");
    }

    Console.Write(": Total- " + sum);

    Console.WriteLine();
}

Output:

Abhimanyu K Vatsa : 97 92 81 90 : Total- 360
Deepak Kumar : 70 56 87 69 : Total- 642
Mohit Kumar : 78 76 81 56 : Total- 933
Geeta K : 95 81 54 67 : Total- 1230

In above query, we have Mark field that will produce a list and that’s why we need to use nested foreach loop to get the list item and at the same time we are adding mark items.

I hope you will find it useful. Thanks for reading.

Comments

Popular posts from this blog

Migrating database from ASP.NET Identity to ASP.NET Core Identity

Customize User's Profile in ASP.NET Identity System