Situation
I have list of objects, and the linq query I am currently using is counting every item up twice. That happens because the data is setup that way. Every PO number will have two lines, and I am counting both. I only need to count one.
PO Number Pallets
123 5
123 5
234 8
234 8
345 2
345 2
Linq Query
Pallets = (from o in this.OrdersModel
where o.Pallets != null
select double.Parse(o.Pallets))
.Sum();
Assuming each object in the set is an OrderModel, when this query is run it will return 30 (all the rows added up)
Desired Outcome
The correct number of pallets would be 15, add up each PO pallets once.
Instead what I would like to happen is a way to select distinct po number, and then add up the pallets. It would be very easy to add this condition in straight SQL, but I have the slightest idea on how to do it in Linq.
Question
- Is there a quick and easy way to do a select distinct po number using Linq?
- If not, what would be the best way to accomplish something like this?
You can use
GroupBy
:But you should probably try to fix your model so you don't get duplicate records in the first place!