Menase
Menase

Reputation: 33

Get Average TimeSpan from a Group

I need to retrieve an average TimeSpan from a List of grouped objects, but have no idea where to start.

Each object in the list has a property of type TimeSpan and I've grouped the List by another property. Now I need the average TimeSpan from each group.

List<Item> Items = new List<Item>();
Item _item1 = new Item { Category = "A", Duration = _someTimeSpan1};
Item _item2 = new Item { Category = "B", Duration = _someTimeSpan2};
Item _item3 = new Item { Category = "A", Duration = _someTimeSpan3};
Items.Add(_item1);
Items.Add(_item2);
Items.Add(_item3);

var _groupedItems = Items.GroupBy(i => i.Category);

In the above example _item1 and _item3 are grouped on Category and I need the average of Duration for those two items that are in the group.

Any help is appreciated.

Upvotes: 1

Views: 376

Answers (3)

arunlalam
arunlalam

Reputation: 1848

var _groupedItems = Items.GroupBy(i => i.Category)
    .Select(g => new { Cat = g.Key, 
    Avg = new TimeSpan(Convert.ToInt64(g.Select(x=>x.Duration.Ticks).Average())) });

Upvotes: 2

Joel Coehoorn
Joel Coehoorn

Reputation: 416149

foreach (var group in _groupedItems) {
   var avg = TimeSpan.FromSeconds(group.Average(i => i.Duration.TotalSeconds));
}

Upvotes: 3

dwonisch
dwonisch

Reputation: 5795

That should do the trick:

foreach (var group in _groupedItems){
    Console.WriteLine(group.Average(g => g.Duration.TotalMilliseconds));
}

Upvotes: 0

Related Questions