The KeyValuePairs and LINQ

c# entity-framework linq

Question

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?

1
4
9/10/2015 7:30:12 AM

Accepted Answer

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
4
1/20/2012 2:45:46 AM

Popular Answer

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));


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow