LINQ和KeyValuePairs

pro*_*mad 4 c# linq entity-framework

我正在尝试计算一组中的项目.所以我有这个LINQ to Entities查询:

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

但它不起作用,因为LINQ to Entities只接受参数初始化器或无参数构造器.所以我创建了一个简单的类来包含KeyValuePair类型:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并将查询更改为:

var qry2 = from c in qry
           group c by c.Content.DownloadType into grouped
           select new ValueCount
           {
               Key = grouped.Key,
               Value = grouped.Count()
           }.ToKeyValuePair();
Run Code Online (Sandbox Code Playgroud)

但仍然行不通.它说它无法识别方法ToKeyValuePair()

如何从LINQ to Entities查询中收集KeyValuePairs?

Muh*_*han 5

一旦从db中返回结果,就必须调用方法,并且可以通过使用ToList()强制查询然后执行select来为每个项调用方法来执行此操作.

   (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());
Run Code Online (Sandbox Code Playgroud)

就像埃里克在评论中正确地说的那样,你可以摆脱你的自定义类并做类似的事情

   (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));
Run Code Online (Sandbox Code Playgroud)

  • 似乎不再需要ValueCount类.只需使用匿名类型并删除额外的代码. (4认同)