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