c# - Linq Groupby 分类但我如何操作集合中的值

标签 c# .net linq

我有一个可观察的拍卖类型拍卖,看起来像

public class Auction
{
     public int GroupId {get; set;}
     public DateTime Date {get; set;}
     public string Hour {get; set;}
     public decimal Offer {get; set;}
     public decimal Bid {get; set;}
     public decimal OfferPrice {get; set;}
     public decimal BidPrice {get; set;}
}

该集合包含以下数据,

Group Id    Date    Hour    Offer   Bid Offer Price Bid Price
1   27/06/2013  00:00   5.556   86.3    250 0
1   27/06/2013  00:15   0   0   250 0
1   27/06/2013  00:30   0   0   250 0
1   27/06/2013  00:45   0   0   250 0
1   27/06/2013  01:00   0   0   250 0
1   27/06/2013  01:15   5.556   86.3    250 0
2   27/06/2013  01:30   8.68    19.9    100 20
2   27/06/2013  01:45   0   0   100 20
2   27/06/2013  02:00   8.68    19.9    100 20
2   27/06/2013  02:15   0   0   100 20
2   27/06/2013  02:30   8.68    19.9    100 20
2   27/06/2013  02:45   0   0   100 20
2   27/06/2013  03:00   8.68    19.9    100 20
3   27/06/2013  03:15   87.14   87.1    150 0
3   27/06/2013  03:30   0   0   150 0
3   27/06/2013  03:45   0   0   150 0
3   27/06/2013  04:00   0   0   150 0
3   27/06/2013  04:15   0   0   150 0
3   27/06/2013  04:30   0   0   150 0
3   27/06/2013  04:45   0   0   150 0
3   27/06/2013  05:00   0   0   150 0

现在我要做的是,

  • 按 GroupId 分组收集,所以我得到 3 个 block ,其中一个 GroupId = 1、GroupId =2 和 GroupId = 3。
  • 然后我需要将不在组 1 中的所有内容设置为零并将其添加到组 1。

例子,

  • 第 1 组中绿色的所有内容都按原样复制,然后第 1 组附加其余数据,但设置为零。
  • 第 2 组和第 3 组类似。

enter image description here

通过 Linq 执行此操作的最佳方法是什么?

需要添加结果的集合是BOD类型,它包含

Public class BOD
{
    public DateTime Date {get; set;}
    public string Time {get; set;}
    public decimal Volume {get; set;}
    public decimal Price {get; set;}
}

最佳答案

您可以将拍卖列表加入到唯一的 GroupId 列表中:

var q = (from a in Auctions
         from g in (Auctions.Select(aa=>aa.GroupId).Distinct())
         orderby g, a.Date, a.Hour
         select new Auction
             {
                  GroupId = g,
                  Date = a.Date,
                  Hour = a.Hour,
                  Offer      = a.GroupId == g ? a.Offer : 0,
                  Bid        = a.GroupId == g ? a.Bid : 0,
                  OfferPrice = a.GroupId == g ? a.OfferPrice : 0,
                  BidPrice   = a.GroupId == g ? a.BidPrice : 0
              }

关于c# - Linq Groupby 分类但我如何操作集合中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17426853/

相关文章:

c# - 使用StreamReader复制图像时损坏

c# - Win8与WP8共享MVVM(一页2页)

.net - 托管在 Windows 服务中的 Kestrel 的 Windows 身份验证

.net - 使用 .NET 项目文件和架构?

c# - 我将如何获得特定列的仅选定行的总和?

c# - LinQ 查询简单的 Where 子句和许多过滤条件

asp.net - 在 Asp.Net MVC Controller 中反序列化 JSON 对象

c# - 在 C# 中定位安装程序路径

c# - 使用 SerialPort 禁用 EOF (0x1A)

c# - Blazor:范围类型输入保持场景(可能吗?)