The KeyValuePairs and LINQ

c# entity-framework linq

Question

I'm attempting to count a set of objects. I thus have this LINQ to Entities program.

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

However, LINQ to Entities only supports constructors with no parameters or parameter initializers, thus it doesn't work. So I made a simple class to include 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);
    }
}

Changing the inquiry 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();

Still, it doesn't function. It claims that it is unaware of the ToKeyValuePair function ()

How may a LINQ to Entities query return KeyValuePairs?

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

Accepted Answer

Try includingAsEnumerable() to keep your code separate from EFs:

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

Once you obtain the database results returned, you must call your function. You may do this 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());

You may eliminate your own class, as Eric correctly points out in the comments, 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