Friday, 18 October 2013

LINQ query to create Dictionary

Assume you have a List<Customer> where Customer has the following properties.
Customer {
int CustomerId,
string Name, 
string Country, 
string Email,
string Phone
}

If you want to create a Dictionary of all customers who has an email address, i.e. Dictionary then you can use the below syntax.

Dictionary customerEmails = (from Customer customer in customers
                            where string.IsNullOrEmpty(customer.Email)
 select new { customer.CustomerId, customer.Email})
.ToDictionary(customer => customer.CustomerId, customer => customer.Email);

Below example shows how this can be done using Lambda Expression

Dictionary customerEmails =
Customers.FindAll(customer => !string.IsNullOrEmpty(customer.Email))
.ToDictionary(customer => customer.CustomerId, customer.Email);

No comments:

Post a Comment