【问题标题】:C# Linq group by multiple column getting No row with the given identifier existsC#Linq按多列分组得到不存在具有给定标识符的行
【发布时间】:2016-08-11 13:38:17
【问题描述】:

之前我提出了一个关于如何在 c# 中使用 linq 进行分组的问题。下面是链接。 现在,当我的按键组之一为空时,我收到错误消息。 基本上我

var result = collection.GroupBy(item => new { item.PNO, item.GCode })
          .Select(grouping => new 
          {
              PNO = grouping.Key.PNO,
              GCode = grouping.Key.GCode,//when this GCode is null, getting error
              Options = grouping.Select(item => new { Color = item.Color, Size = item.Size, Amount = item.Amount }).ToList()
          }).ToList();

我得到的错误类似于:

No row with the given identifier exists[....]

谁能建议我解决这个问题?

C# Linq how to use group by to get the desired output

谢谢

【问题讨论】:

  • 当我在一些示例数据上运行该代码时,GCode null 它可以工作。请显示您拥有的数据。
  • 基本上我是从 NHibernate 查询结果中获取数据的。

标签: linq c#-4.0


【解决方案1】:

搜索错误时发现this和this。

另一种可能的解决方案是使用??

var result = collection.GroupBy(item => new { item.PNO ?? string.Empty, item.GCode ?? string.Empty})
          .Select(grouping => new 
          {
              PNO = grouping.Key.PNO,
              GCode = grouping.Key.GCode,//when this GCode is null, getting error
              Options = grouping.Select(item => new { Color = item.Color, Size = item.Size, Amount = item.Amount }).ToList()
          }).ToList();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-02
    • 2013-08-28
    • 2013-10-11
    • 2022-01-24
    • 2017-05-13
    • 1970-01-01
    相关资源
    最近更新 更多