1

我有一个Dictionary<string, CachedImage>我想对项目进行分组,计算组中的项目数,如果计数大于 6500 则遍历每个组。

该类CachedImage包含我感兴趣的PathAnd属性。ExpiresUtc

遗憾的是,我的 Linq-fu 缺少复杂的查询,所以就我所知,我想我已经搞砸了。我假设我想要的是可能的。

任何帮助将不胜感激,尤其是快速演练。

Regex searchTerm = new Regex(@"(jpeg|png|bmp|gif)");
var groups= PersistantDictionary.Instance.ToList()
            .GroupBy(x => searchTerm.Match(x.Value.Path))
            .Select(y => new
                           {
                            Path = y.Key,
                            Expires = y.Select(z => z.Value.ExpiresUtc),
                            Count = y.Sum(z => z.Key.Count())
                           })
            .AsEnumerable();
4

1 回答 1

2

试试这个:

var groups = PersistantDictionary.Instance.ToList()
        .GroupBy(x => searchTerm.Match(x.Value.Path).Value)
        .Where(g => g.Count() > 6500);

foreach (var group in groups)
{
    Console.WriteLine("{0} images for extension {1}", group.Count(), group.Key);

    foreach (KeyValuePair<string, CachedImage> pair in group)
    {
        //Do stuff with each CachedImage.
    }
}

所以要打破这个:

PersistantDictionary.Instance.ToList()

产生一个列表KeyValuePair<string, CachedImage>

.GroupBy(x => searchTerm.Match(x.Value.Path).Value)

按正则表达式匹配的对列表进行Path分组CachedImage。请注意,我使用了该Value属性 - 该Match方法返回一个Match对象,因此最好按匹配的实际文本进行分组。这一步的结果将是一个IEnumerable<IGrouping<string, KeyValuePair<string, CachedImage>>>

.Where(g => g.Count() > 6500);

这可确保仅检索具有 > 6500 个项目的组。

于 2013-03-13T01:46:35.670 回答