Reputation: 10635
I have a Dictionary<string, CachedImage>
with which I'd like to group the items, count the number of items in the group and iterate through each group if the count is greater than 6500.
The CachedImage
class contains Path
And ExpiresUtc
properties that I am interested in.
My Linq-fu is sadly lacking with complex queries so this is as far as I have got and I think I've already messed up. I'm assuming what I want is possible.
Any help would be appreciated, especially with a quick walkthrough.
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();
Upvotes: 1
Views: 1710
Reputation: 14938
Try this:
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.
}
}
So to break this down:
PersistantDictionary.Instance.ToList()
Produces a list of KeyValuePair<string, CachedImage>
.
.GroupBy(x => searchTerm.Match(x.Value.Path).Value)
Groups the list by the Regex match against the Path
of the CachedImage
. Note that I have used the Value
property - the Match
method returns a Match
object, so it would be best to group by the actual text of the match. The outcome of this step will be an IEnumerable
of <IGrouping<string, KeyValuePair<string, CachedImage>>>
.
.Where(g => g.Count() > 6500);
This ensures that only those groups with > 6500 items will be retrieved.
Upvotes: 2