LINQ and KeyValuePairs

I am trying to count the elements 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 this does not work, because LINQ to Entities accepts only parameter initializers or constructors without parameters. So I created a simple class to omit 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 request 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 does not work. It says that it does not recognize the ToKeyValuePair () method

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

+4
source share
2 answers

Try adding AsEnumerable() to extract code from EF:

 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
source

You must call your method as soon as you have the results from the database, and you can do this by querying with ToList () and then making a choice to call your method for each element.

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

As Eric correctly 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)); 
+5
source

Source: https://habr.com/ru/post/1391914/


All Articles