Having trouble expressing a group query in LINQ
I have a 2 types:
public class TimedValue
{
public DateTime TimeStamp { get; set; }
public double Value { get开发者_如何学运维; set; }
}
public class Stats
{
IList<TimedValue> Values { get; set; }
... // some other fields
}
Multiple instances of Stats are stored in an IEnumerable collection object. I'm trying to come up with a LINQ query that would give me a chronological Value totals over all Stats instances. Meaning it would go through every TimedValue in every Stats object, and if their TimeStamps match, it will add the Value fields. So at the end I will get a chronologically (oldest to newest) grouped List of doubles.
Being weak at LINQ, I am failing at this. I only got as far as to do:
.Select(stat => stat.Values)
To project down to the:
List<List<Value>>
Which is the subset of Stats object I need, but I can't figure out how to group the total values I need from this.
Example (since there is some confusion as to what I meant):
Suppose we have 2 instances of stats, I'm simplifying notation here, just to make examples short:
Stats1: Values = {{ "Monday", 1.1 }, {"Tuesday", 2.2}}
Stats2: Values = {{ "Monday", 1.1 },{"Tuesday", 2.2}, {"Friday", 3.3}}Result should be a list of doubles: {2.2, 4.4, 3.3}
This should give you a list of doubles containing the sums:
statList.SelectMany(stat => stat.Values)
.GroupBy( x => x.TimeStamp)
.OrderBy( g => g.Key)
.Select( g => g.Sum(x => x.Value));
.ToList();
If you didn't want the sums (not totally clear in the question), this would give you just the list of groupings:
var timeStampGroups = statList.SelectMany(stat => stat.Values)
.GroupBy( x => x.TimeStamp)
.OrderBy( g => g.Key)
.ToList();
Updated to return a List of doubles as requested.
This should do the trick:
var values = (from stat in statsCollection
from value in stat.Values
//group the values by the timestamp
group value by value.TimeStamp into grouping
orderby grouping.Key
select grouping.Sum(v => v.Value)).ToList();
Here's the output:
精彩评论