0

Earlier I raised an issue about how to group by using linq in c#. Below is the link. Now I am getting an error when one of my group by key is null. basically I

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();

Error I am getting is something like:

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

Can anyone please suggest me a solution for this?

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

Thanks

Community
  • 1
  • 1
Mukil Deepthi
  • 6,072
  • 13
  • 71
  • 156

1 Answers1

0

When searching for the error I found this and this.

Another possible solution is to use ??

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();
Community
  • 1
  • 1
Gilad Green
  • 36,708
  • 7
  • 61
  • 95