LINQ和KeyValuePairs

时间:2012-01-19 19:50:07

标签: 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());

但它不起作用,因为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);
    }
}

并将查询更改为:

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?

2 个答案:

答案 0 :(得分: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());

就像Eric在评论中正确地说的那样,你可以摆脱你的自定义类并执行类似

的操作
   (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));

答案 1 :(得分:4)

尝试添加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