2

Currently I am looking for a way to get the sum of all piece counts from an enumerable while ignoring duplicates, all this while using method syntax. As things are right now my code will work, but I realize this is only temporary. More on this later.

Lets use the following class as an example

internal class Piece
{
    public int Count { get; set; }
    public DateTime Date { get; set; }
    public string Description { get; set; }   
}

This class is then used to create a list with the following information

List<Piece> pieces = new List<Piece>
{
    new Piece(41,DateTime.Parse("2019-07-12"),"BB"),
    new Piece(41,DateTime.Parse("2019-07-12"),"BB"),
    new Piece(21,DateTime.Parse("2019-07-12"),"JP"),
    new Piece(23,DateTime.Parse("2019-07-14"),"AA")
};

To do the sum, I came up with the following

int total = pieces.Where(x => x.Count > 0)
                  .GroupBy(x => x.Count, x => x.Date, 
                           (piece, date) => new { Count = piece,Date = date})
                  .Sum(x => x.Count);

This is where things get tricky. If another piece were to be added with as follows

new Piece(23,DateTime.Parse("2019-07-14"),"AB") 

that piece would be ignored due to how I am grouping. This is far from ideal.

I have found the following way to group by several columns

GroupBy( x => new {x.Count,x.Date,x.Description})

But I have found no way make it so I can use Sum on this Grouping. This grouping using the AnonymousType does not let me declare local variables (piece,date) as I am able to do in the prior GroupBy (as far as I know). For now the code that I have will do the trick but it is only a matter of time before that is no longer the case.

Some extra details.

I am manipulating a query result using Razor, and I have no control on the data that I get from the server. Manipulating the data using linq is basically the only way I have at the moment.

Any help is greatly appreciated

Gilad Green
  • 36,708
  • 7
  • 61
  • 95

1 Answers1

2

For the count you just need this query:

int total = pieces
    .Where(x => x.Count > 0)
    .GroupBy(x => new { x.Count, x.Date, x.Description })
    .Sum(g => g.Key.Count);

So you can access all key properties of the grouping.

This returns 85 for your initial sample and 108 if you add the new piece.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • as i understood you need sum by broup, not a totals: ```C# pieces.Where(x => x.Count > 0) .GroupBy(x => new { x.Count, x.Date, x.Description }) .Select(x => new {obj = x.Key, GroupingSum= x.Sum(s => s.Count)}); ``` i attached image to explain how it grouped – Power Mouse Aug 07 '19 at 14:48
  • Thanks @Tim Schmelter. I was actually looking into what that Key property actually did but you definitely beat me to it! – Wence Peraza Aug 07 '19 at 15:11