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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With