Customizing LINQ’s "select" Statement: Part 8

This is eighth part of the "LINQ" series of articles that I have started from here. In the previous article we explored how to join data from multiple data sources using "Concat" key. Now, in this article you will learn how to customize the LINQ's "select" statement to select a subset of each Source Element.


Assuming the following as the data source:


Student.cs

 

    class Student

    {

        public int ID { getset; }

        public string Name { getset; }

        public string Address { getset; }

        public List<int> Marks { getset; }

    }


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 the name of the students then use the 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 the name and address of the student then use the 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 the 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 the above query, we have the Mark field that will produce a list and that's why we need to use a 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.

Up Next
    Ebook Download
    View all
    Learn
    View all