LINQ is useful for querying as we can query different types of lists in C# or any other .NET language.We can select values from a list using Select operator in LINQ.But sometimes we need to project or select multiple columns or fields in a collection.
Suppose we have a List of items and we want want search some values in the list.We can easily do that using LINQ select operator
For example if we have an Employee class declared as:
class Employee { public string Name { get; set; } public string Id { get; set; } public string Dept { get; set; } }
we have list of employees declared as:
var employeesLst = new List<Employee> { new Employee { Name = "emp1", Id = "1",Dept="Accounts" }, new Employee { Name = "emp2", Id = "2",Dept="Finance" }, new Employee { Name = "emp3", Id = "3",Dept="Finance" }, };
then we can filter the employees based on the Id
var selectedLst=from item in employeesLst select item.Name;
But if now we want to select multiple Dept and Name fields then we can not use this since this will be invalid syntax in LINQ:
var selectedLst=from item in employeesLst select item.Id,item.Name;
to handle such scenario we can use the anonymous type using the following syntax:
var selectedLst=from item in employeesLst select new { item.Id, item.Name };