Is it possible to use LINQ to get data from DB and store it in Dictionary.
I can do LINQ and store it in a List<Class_B>
and then iterate through the list and store it in Dictonary<Class_A,List<Class_B>>
. But is it possible to directly store in the Dictionary?
Asked
Active
Viewed 783 times
-1

John Saunders
- 160,644
- 26
- 247
- 397

user3344591
- 567
- 5
- 21
-
5Yes, use the `ToDictionary()` method. http://msdn.microsoft.com/en-us/library/system.linq.enumerable.todictionary%28v=vs.100%29.aspx – Ben Robinson Dec 23 '14 at 17:05
-
1have a look at `ToDictonary` – Daniel A. White Dec 23 '14 at 17:05
-
I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Dec 23 '14 at 17:07
1 Answers
0
System.Linq.Enumerable has a ToDictionary method.
Here's an example from dotnetperls.com:
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main()
{
// Example integer array.
int[] values = new int[] { 1, 3, 5, 7 };
// First argument is the key, second the value.
Dictionary<int, bool> dictionary = values.ToDictionary(v => v, v => true);
// Display all keys and values.
foreach (KeyValuePair<int, bool> pair in dictionary)
{
Console.WriteLine(pair);
}
}
}

Andy West
- 12,302
- 4
- 34
- 52