Question

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

  1. Is there a quick and easy way to do a select distinct po number using Linq?
  2. If not, what would be the best way to accomplish something like this?
Was it helpful?

Solution

Is there a quick and easy way to do a select distinct

You can use GroupBy:

Pallets = (from o in this.OrdersModel.GroupBy(o => o.PONumber).Select(g => g.First())
           where o.Pallets != null
           select double.Parse(o.Pallets))
           .Sum();

But you should probably try to fix your model so you don't get duplicate records in the first place!

OTHER TIPS

Try this:

Pallets = this.OrdersModel
                .Where(x=>x.Paletts!=null).Distinct()
                .Sum(x=>double.Parse(x.Pallets));

As here is said, you need to implement IEquatable interface, so you can define which items are duplicates (thanks to Raphaël for reminding)

Well, if you want a fast solution: Pallets = Pallets /2 But this is a quck fix , you should use distinct.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top