how to use linq with dictionary
Many a times we may have to use a Dictionary object as the data source. As the dictionary implements IEnumerable<T> interface, we can use LINQ to query against the dictionary. In the example given below, the dictionary holds customer names and their closing balances.
Dictionary CustomerBalances;
CustomerBalances = new Dictionary();
CustomerBalances.Add("Customer1", 100.0);
CustomerBalances.Add("Customer2", 237.0);
CustomerBalances.Add("Customer3", 456.2);
CustomerBalances.Add("Customer4", 890.4);
CustomerBalances.Add("Customer5", 1000.0);
The above code creates a dictionary CustomerBalances of the type Dictionary
where key is the customer name and the value is the closing balance. The above code also adds items to the Dictionary.
var customerbalances =
from bal in CustomerBalances
where bal.Value > 250
select bal.Key;
foreach (var row in customerbalances)
{
Console.WriteLine(row);
}
Console.ReadLine();
The above code retrieves names of the customers with closing balance above 250 from the dictionary. The data present in the dictionary CustomerBalances and the query retrieves the list of all customer names.