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
public int ID { get; set; }
public string Name { get; set; }
public string Address { get; set; }
public List<int> Marks { get; set; }
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}}
Now, if you want to select only the name of the students then use the following LINQ query:
var query = from student in students
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};
Console.WriteLine(e.Name + " from " + e.Address);
Abhimanyu K Vatsa from Bokaro
Deepak Kumar from Dhanbad
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};
Console.Write(e.Name + " : ");
foreach (var m in e.Mark)
Console.Write(": Total- " + sum);
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.