using todictionary method
Many a times, it is beneficial to convert the result of a linq query to a dictionary. We can convert the query results into different collections by using different methods. In this example, we use ToDictionary method. The ToDictionary method which is an extension method. This method contains two arguments, the first argument is the key and second argument is the value.
The Dictionary we have used here is a string Dictionary. Note that, dictionaries are frequently used for lookups.
Observe that the below given query is a LINQ To SQL query and it retrieves customer name and address from the Customer table. Using for each loop we have enumerated the dictionary.
// Convert query result to dictionary
string connectionString = "Data Source=LocalHost; Initial CataLog=SalesOrderManagement;Integrated Security=True";
DataContext db = new DataContext(connectionString);
Table Customers = db.GetTable();
var query =
from c in Customers
new { c.Name, c.Address };
Dictionary d = query.ToDictionary(k => k.Name, k => k.Address);
foreach (var pair in d)
{
Console.WriteLine("{0}, {1}",pair.Key,pair.Value);
}
using toarray method
ToArray is a Linq extension method and it converts any IEnumerable type to an array. In the example given below the LINQ query result is of IEnumerable type and we use Toarray to convert the query result into an array. After converting the query to an array, we store it in memory. The ToArray extension method creates a buffer array to which the elements query result are copied. When we call ToArray LINQ query is executed immediately. The example discussed is based on the SalesOrderManagement domain model.
Example for Convert LINQ query results into an array with ToArray method
SalesDBDataContext dataContext = new SalesDBDataContext();
var custQuery = from cust in dataContext.Customers
select cust;
Customer[] qArray = custQuery.ToArray();
foreach (var pair in qArray)
{
Console.WriteLine(pair.CustomerId);
}