Check the following program below from the book “Essential LINQ”:
class Customer
{
public string CustomerID {get;set;}
public string ContactName {get;set;}
public string City {get;set;}
public static List<Customer> GetCustomers()
{
return new List<Customer>
{
new Customer {CustomerID = "ALFKI", ContactName = "Maria Anders", City = "Berlin"},
new Customer {CustomerID = "ANATR", ContactName = "Sns Trujillo", City = "Mexico D.F."},
new Customer {CustomerID = "ANTON", ContactName = "Antonio Moreno", City = "Mexico D.F."}
};
}
}
void Main()
{
var query = from c in Customer.GetCustomers()
where c.City == "Mexico D.F."
select new { c.City, c.ContactName};
foreach (var cityandcontact in query)
{
Console.WriteLine(cityandcontact);
}
}
In the LINQ Query, why it gives me error if I remove “new” from line:
select new {c.City, c.ContactName};
why we can’t just write like this
select c.City, c.ContactName;
what is the logic here?
Queries return enumerations of objects of the same class. It can be any class, but it needs to be just one for all rows. You cannot return pairs of objects (a city and a contact name) without combining them into a single object. In this case, you are combining them into an object of anonymous type, with two properties.
On a side note, there is no advantage to using
Selectmethod at all, because both properties come from the sameCustomerclass. In fact, there is less efficient than returning customer objects unchanged, like this: