// Will aggregate metrics for a single tag of a single template IEnumerable <Metric> AggregateTag(IEnumerable <Metric> metrics, IEnumerable <string> targetMetricNames, string targetTag, IAggregator aggregator) { var aggregateValues = new DefaultDictionary <AggregateMetric, IAggregator>(_ => aggregator.New()); foreach (Metric metric in metrics) { // if metric is the aggregation target and it has a tag that should be aggregated if (targetMetricNames.Contains(metric.Name) && metric.Tags.ContainsKey(targetTag)) { var aggregateMetric = new AggregateMetric(metric, targetTag); aggregateValues[aggregateMetric].PutValue(metric.Value); } else { yield return(metric); } } // aggregate all and construct new metrics from result foreach (var aggregatePair in aggregateValues) { double aggregatedValue = aggregatePair.Value.GetAggregate(); yield return(aggregatePair.Key.ToMetric(aggregatedValue)); } }