The actual query I am trying to write is slightly trickier than the title suggests. I have a list of orders like such: List<Order>, an order looks like this:
public class Order
{
private StockCodes _stockCode;
private bool _bidSide;
private int _volume;
private decimal _price;
}
I need to publish the best bid price and volume and the best sell price and volume given a specific stock code. The best bid price is defined as the HIGHEST price where bidSide is true. The best sell price is defined as the LOWEST price where bidSide is false.
For example given the following data for stock code “ABC”:
{ bidSide: true, volume: 25, price: 25 }
{ bidSide: true, volume: 25, price: 25 }
{ bidSide: true, volume: 25, price: 5 }
{ bidSide: false, volume: 100, price: 1 }
{ bidSide: false, volume: 50, price: 2}
{ bidSide: false, volume: 75, price: 8 }
Best bid: price 25, volume 50 (since there are 2 orders at the highest price)
Best sell: price 1, volume 100 (since there is just 1 order at the lowest price)
Lastly, I need to account for when there are no bid or sell orders. Efficiency is of high priority, so If I am able to do this in one linq statement that would be preferred.
To do this efficiently, you really only want to iterate over the data once. Unfortunately, that makes it a real pain to implement with LINQ, as there’s quite a lot of work to do.
Personally I would suggest that you don’t do this with LINQ – you could implement it with
Aggregate, but it wouldn’t be terribly pleasant. It’s not too bad with a simpleforeachloop though. Something like:Doing it as efficiently as possible in LINQ would effectively mean putting all that logic in the loop into a function to pass into
Aggregate– and you’d probably want to create a custom value type to hold the four values, to avoid creating more objects than you need to. That may be overkill, but you did say you wanted it as efficient as possible…