Linq-to-SQL ToDictionary()

C#LinqLinq to-Sql

C# Problem Overview


How do I properly convert two columns from SQL (2008) using Linq into a Dictionary (for caching)?

I currently loop through the IQueryable b/c I can't get the ToDictionary method to work. Any ideas? This works:

var query = from p in db.Table
            select p;

Dictionary<string, string> dic = new Dictionary<string, string>();

foreach (var p in query)
{
    dic.Add(sub.Key, sub.Value);
}

What I'd really like to do is something like this, which doesn't seem to work:

var dic = (from p in db.Table
             select new {p.Key, p.Value })
            .ToDictionary<string, string>(p => p.Key);

But I get this error: Cannot convert from 'System.Linq.IQueryable' to 'System.Collections.Generic.IEnumerable'

C# Solutions


Solution 1 - C#

var dictionary = db
    .Table
    .Select(p => new { p.Key, p.Value })
    .AsEnumerable()
    .ToDictionary(kvp => kvp.Key, kvp => kvp.Value)
;

Solution 2 - C#

You are only defining the key, but you need to include the value also:

var dic = (from p in db.Table
             select new {p.Key, p.Value })
            .ToDictionary(p => p.Key, p=> p.Value);

Solution 3 - C#

Thanks guys, your answers helped me fix this, should be:

var dic = db
        .Table
        .Select(p => new { p.Key, p.Value })
        .AsEnumerable()
        .ToDictionary(k=> k.Key, v => v.Value);

Solution 4 - C#

Why would you create an anonymous object for every item in the table just to convert it?

You could simply use something like: IDictionary<string, string> dic = db.Table.ToDictionary(row => row.Key, row => row.Value); You may need to include an AsEnumerable() call between Table and ToDictionary(). I don't know the exact type of db.Table.


Also correct the first sample, your second loop variable is mismatching at declaration and usage.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCodewerksView Question on Stackoverflow
Solution 1 - C#yfeldblumView Answer on Stackoverflow
Solution 2 - C#Christian C. SalvadóView Answer on Stackoverflow
Solution 3 - C#CodewerksView Answer on Stackoverflow
Solution 4 - C#TWiStErRobView Answer on Stackoverflow