我正试着在一个小组里数项目。所以我有一个linq to entities查询:

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

但它不起作用,因为linq to实体只接受参数初始值设定项或无参数构造函数。所以我创建了一个简单的类来封装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);
    }
}

并将查询更改为:
var qry2 = from c in qry
           group c by c.Content.DownloadType into grouped
           select new ValueCount
           {
               Key = grouped.Key,
               Value = grouped.Count()
           }.ToKeyValuePair();

但还是不行。它说它无法识别tokeyValuePair()方法
如何从linq to entities查询收集keyvaluepairs?

最佳答案

尝试添加AsEnumerable()以将代码与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

08-28 06:08