我需要一些帮助来汇总我收藏中的数据。
RrvResponse 类
/// <summary>
/// The RRV response.
/// </summary>
public class RrvResponse
{
/// <summary>
/// Initializes a new instance of the <see cref="RrvResponse"/> class.
/// </summary>
public RrvResponse()
{
this.BoDPoints = new ObservableCollection<BidOfferPoint>();
}
/// <summary>
/// Gets or sets the id.
/// </summary>
public string Id { get; set; }
/// <summary>
/// Gets or sets the message date.
/// </summary>
public DateTime MessageDate { get; set; }
/// <summary>
/// Gets or sets the BOD points.
/// </summary>
public ObservableCollection<BidOfferPoint> BoDPoints { get; set; }
}
实现,
var responses = new ObservableCollection<RrvResponse>();
// ....Load responses...
// ...
// ...
响应的数量是 5,所以我在响应中有 5 个 BoDPoints 的 ObservableCollection。
BOD points are,
/// <summary>
/// The bid offer point.
/// </summary>
public class BidOfferPoint
{
/// <summary>
/// Gets or sets the date.
/// </summary>
public DateTime Date { get; set; }
/// <summary>
/// Gets or sets the time.
/// </summary>
public string Time { get; set; }
/// <summary>
/// Gets or sets the volume.
/// </summary>
public decimal Volume { get; set; }
/// <summary>
/// Gets or sets the price.
/// </summary>
public decimal Price { get; set; }
}
示例,
Observable Collection Bod - 1
2013-06-21
00:00
100
10
2013-06-21
00:15
120
15
2013-06-21
00:30
150
9
可观察集合 Bod - 2
2013-06-21
00:00
Observable Collection Bod - 1
2013-06-21
00:00
100
10
2013-06-21
00:15
120
15
2013-06-21
00:30
150
9
40
1
2013-06-21
00:15
10
0.5
2013-06-21
00:30
11
0.1
Observable 集合 Bod - 3
2013-06-15
00:00
100
10
2013-06-15
00:15
120
15
2013-06-15
00:30
150
9
我想按日期分组,然后按时间分组,然后合计卷数。因此,在上面的示例中,应汇总 2013 年 6 月 21 日 00:00 的所有交易量,应汇总 2013 年 6 月 21 日 00:15 的所有交易量。
使用 Linq 执行此操作的最佳方法是什么?
最佳答案
您可以使用SelectMany
聚合项目并在之后对它们进行分组:
var result = responses
.SelectMany(r => r.BoDPoints)
.GroupBy(p => p.Date)
.Select(byDate =>
new
{
Date = byDate.Key,
EntriesByTime = byDate
.GroupBy(p => p.Time)
.Select(byTime =>
new
{
Time = byTime.Key,
TotalVolume = byTime.Sum(p => p.Volume)
})
});
您可以使用以下循环(例如输出总音量)
foreach (var byDate in result)
{
Console.WriteLine("Entries for date " + byDate.Date);
foreach (var byTime in byDate.EntriesByTime)
{
Console.WriteLine("Total volume for time " + byTime.Time + ": " + byTime.TotalVolume);
}
}
关于c# - Linq Groupby Sum 一个嵌套的可观察集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17230694/