programad
programad

Reputation: 1311

LINQ and the KeyValuePairs

I'm trying to count items in a group. So I have this LINQ to Entities query:

var qry2 = from c in qry
           group c by c.Content.DownloadType into grouped
           select new KeyValuePair(grouped.Key,grouped.Count());

But it doesn't work because LINQ to Entities only accepts parameter initializers or parameterless constructors. So I created a simple class to envelop the KeyValuePair type:

public class ValueCount
{
    public string Key { get; set; }
    public int Value { get; set; }

    public KeyValuePair<string, int> ToKeyValuePair()
    {
        return new KeyValuePair<string, int>(this.Key, this.Value);
    }
}

And changed the query to:

var qry2 = from c in qry
           group c by c.Content.DownloadType into grouped
           select new ValueCount
           {
               Key = grouped.Key,
               Value = grouped.Count()
           }.ToKeyValuePair();

But still doesn't work. It says that it doesn't recognizes the method ToKeyValuePair()

How can I collect KeyValuePairs from a LINQ to Entities query?

Upvotes: 4

Views: 11109

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Try adding AsEnumerable() to isolate your code from EF's:

var qry2 = from c in qry
    group c by c.Content.DownloadType into grouped
    select new ValueCount
    {
        Key = grouped.Key,
        Value = grouped.Count()
    }.AsEnumerable()   // This "cuts off" your method from the Entity Framework,
    .Select(vc => vc.ToKeyValuePair()); // letting you nicely complete the conversion in memory

Upvotes: 4

Muhammad Hasan Khan
Muhammad Hasan Khan

Reputation: 35136

You have to call your method once you have the results back from the db and you can do that by forcing the query using ToList() and then doing a select to call your method on each item.

   (from c in qry
   group c by c.Content.DownloadType into grouped
   select new ValueCount
   {
       Key = grouped.Key,
       Value = grouped.Count()
   }).ToList().Select(x=>x.ToKeyValuePair());

Like Eric rightly says in the comments you can get rid of your custom class and do something like

   (from c in qry
   group c by c.Content.DownloadType into grouped
   select new
   {
       Key = grouped.Key,
       Value = grouped.Count()
   }).ToList().Select(x=>new KeyValuePair<string, int>(x.Key, x.Value));

Upvotes: 5

Related Questions