C#:如何使用Enumerable.Aggregate方法

时间:2009-06-09 13:45:24

标签: c# time aggregate

让我说我有这个截肢的Person课程:

class Person
{
    public int Age { get; set; }
    public string Country { get; set; }

    public int SOReputation { get; set; }
    public TimeSpan TimeSpentOnSO { get; set; }

    ...
}

然后,我可以按照AgeCountry进行分组:

    var groups = aListOfPeople.GroupBy(x => new { x.Country, x.Age });

然后我可以输出所有组的声誉总数如下:

foreach(var g in groups)
    Console.WriteLine("{0}, {1}:{2}", 
        g.Key.Country, 
        g.Key.Age, 
        g.Sum(x => x.SOReputation));

我的问题是,如何获得TimeSpentOnSO属性的总和? Sum方法在这种情况下不起作用,因为它只适用于int等。我以为我可以使用Aggregate方法,但只是认真无法弄清楚如何使用它...我正在尝试各种组合的各种属性和类型,但编译器只是不会识别它。

foreach(var g in groups)
    Console.WriteLine("{0}, {1}:{2}", 
        g.Key.Country, 
        g.Key.Age, 
        g.Aggregate(  what goes here??  ));

我是否完全误解了Aggregate方法?或者发生了什么?是否应该使用其他方法?或者我是否必须为Sum s编写自己的TimeSpan变体?

要添加到混乱中,如果Person是匿名类,例如SelectGroupJoin语句会导致什么?


如果我先在Aggregate属性上执行了Select,我就可以让TimeSpan方法正常工作......但我发现这种烦恼...仍然根本不觉得我理解这个方法......

foreach(var g in groups)
    Console.WriteLine("{0}, {1}:{2}", 
        g.Key.Country, 
        g.Key.Age, 
        g.Select(x => x.TimeSpentOnSO)
        g.Aggregate((sum, x) => sum + y));

5 个答案:

答案 0 :(得分:24)

List<TimeSpan> list = new List<TimeSpan>
    {
        new TimeSpan(1),
        new TimeSpan(2),
        new TimeSpan(3)
    };

TimeSpan total = list.Aggregate(TimeSpan.Zero, (sum, value) => sum.Add(value));

Debug.Assert(total.Ticks == 6);

答案 1 :(得分:14)

g.Aggregate(TimeSpan.Zero, (i, p) => i + p.TimeSpentOnSO)

基本上,Aggregate的第一个参数是初始化器,它在第二个参数中传递的函数中用作“i”的第一个值。它将遍历列表,每次“i”将包含到目前为止的总数。

例如:

List<int> nums = new List<int>{1,2,3,4,5};

nums.Aggregate(0, (x,y) => x + y); // sums up the numbers, starting with 0 => 15
nums.Aggregate(0, (x,y) => x * y); // multiplies the numbers, starting with 0 => 0, because anything multiplied by 0 is 0
nums.Aggregate(1, (x,y) => x * y); // multiplies the numbers, starting with 1 => 120

答案 2 :(得分:2)

克里斯和丹尼尔斯的回答为我解决了这个问题。我需要初始化TimeSpan,我做错了顺序。解决方案是:

foreach(var g in groups)
    Console.WriteLine("{0}, {1}:{2}", 
        g.Key.Country, 
        g.Key.Age, 
        g.Aggregate(TimeSpan.Zero, (sum, x) => sum + x.TimeSpentOnSO));

谢谢!

还有...... D'oh!

答案 3 :(得分:1)

您可以撰写TimeSpan Sum方法......

public static TimeSpan Sum(this IEnumerable<TimeSpan> times)
{
    return TimeSpan.FromTicks(times.Sum(t => t.Ticks));
}
public static TimeSpan Sum<TSource>(this IEnumerable<TSource> source,
    Func<TSource, TimeSpan> selector)
{
    return TimeSpan.FromTicks(source.Sum(t => selector(t).Ticks));
}

或者,MiscUtil具有通用的Sum方法,因此Sum应该对TimeSpan工作正常(因为定义了TimeSpan+TimeSpan=>TimeSpan个运算符)。

只是不要告诉我号码......这会吓到我......

答案 4 :(得分:0)

您可以对TimeSpan的其中一个属性求和。例如,您可以像这样得到所代表的TotalHours花费的时间:

g.Sum(x => x.SOReputation.TotalHours)

我相信这会给你你正在寻找的结果,但需要注意的是你必须根据你的需要(小时,分钟,秒,天等)来计算单位。 / p>