0

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?
Liath
  • 9,913
  • 9
  • 51
  • 81
zach
  • 1,281
  • 7
  • 27
  • 41
  • Do you mean distinct? There is a linq method called Distinct() although I use the lambda form so I'd struggle to advise on your query – Liath Dec 18 '13 at 13:59
  • If you have two entries for each PO Number, how do you know which of the two to include in your sum? – Ian Nelson Dec 18 '13 at 14:01
  • 2
    Well, if you want a fast solution: Pallets = Pallets /2; – PeterRing Dec 18 '13 at 14:01
  • @IanNelson There are a few ways, but initially we do not have the data structure in place to need to worry about that yet. – zach Dec 18 '13 at 14:49

3 Answers3

2

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)

Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
2

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!

D Stanley
  • 149,601
  • 11
  • 178
  • 240
  • @D Stanley That is definately the best approach. We have not quite figured that step out yet. But we will need to eventually not populate every record. Thanks for the answer – zach Dec 18 '13 at 15:26
0

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

PeterRing
  • 1,767
  • 12
  • 20