Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 331
programad Avatar asked Jan 18 '23 17:01

programad


1 Answers

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));
like image 85
Muhammad Hasan Khan Avatar answered Jan 24 '23 16:01

Muhammad Hasan Khan