How to get the sum of the volume of the highest and cheapest items in linq

The actual query I'm trying to write is a little more complicated than the name suggests. I have a list of such orders:, the List<Order>order is as follows:

public class Order
{
    private StockCodes _stockCode;
    private bool _bidSide;
    private int _volume;
    private decimal _price;
}

I need to publish the best price and volume of the offer, as well as the price and volume of the selling price, taking into account a specific stock code. The best bid price is defined as the HIGH price, where bidSide is true. The best selling price is defined as LOW price, where bidSide is false.

For example, the following data is 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 price: price 1, volume 100 (since there is only 1 order at the lowest price)

, , . , , linq, .

+3
3

, . , LINQ, .

, LINQ - Aggregate, . foreach. - :

int buyVolume = -1;
int sellVolume = -1;
decimal buyPrice = decimal.MinValue;
decimal sellPrice = decimal.MaxValue;

foreach (var order in orders)
{
    if (order.bidSide)
    {
        if (order.Price > buyPrice)
        {
            buyPrice = order.Price;
            buyVolume = order.Volume;
        }
        else if (order.Price == buyPrice)
        {
            buyVolume += order.Volume;
        }
    }
    else
    {
        if (order.Price < sellPrice)
        {
            sellPrice = order.Price;
            sellVolume = order.Volume;
        }
        else if (order.Price == sellPrice)
        {
            sellVolume += order.Volume;
        }
    }
}

// Check sellVolume == -1 to verify whether we've seen any sale orders
// Check buyVolume == -1 to verify whether we've seen any buy orders
// Use buyPrice/buyVolume and sellPrice/sellVolume otherwise

LINQ , Aggregate, , , , , . , , , ...

+6
HIGHEST = orders.Max(x => x.bidSide ? x.price : (decimal?)null) ?? 0M

LOWEST.

Linq2SQL , . , . ( : ). SQL .

0

LINQ ...

var bids = (from o in orders
                where o.StockCode == "ABC" && o.BidSide == true
                group o by o.Price)
                .OrderByDescending(g => g.Key)
                .FirstOrDefault();
var bidVolume = bids != null ? new Order { Price = bids.Key, Volume = bids.Sum(g => g.Volume) } : null;

var sells = (from o in orders
                where o.StockCode == "ABC" && o.BidSide == false
                group o by o.Price)
                .OrderBy(g => g.Key)
                .FirstOrDefault();
var sellVolume = sells != null ? new Order { Price = sells.Key, Volume = sells.Sum(g => g.Volume) } : null;
0

All Articles