简体   繁体   English

LINQ和KeyValuePairs

[英]LINQ and the KeyValuePairs

I'm trying to count items in a group. 我正在尝试计算一组中的项目。 So I have this LINQ to Entities query: 所以我有这个LINQ to Entities查询:

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. 但它不起作用,因为LINQ to Entities只接受参数初始化器或无参数构造器。 So I created a simple class to envelop the KeyValuePair type: 所以我创建了一个简单的类来包含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);
    }
}

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() 它说它无法识别方法ToKeyValuePair()

How can I collect KeyValuePairs from a LINQ to Entities query? 如何从LINQ to Entities查询中收集KeyValuePairs?

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. 一旦从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());

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

Try adding AsEnumerable() to isolate your code from EF's: 尝试添加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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM