按计数对象分组

时间:2014-12-11 15:37:58

标签: c# linq

我想计算我分组的项目数。我有一个类型为Liquidity Builder的列表:

public class LiquidityBuilder
{
private string _lp;
private string _timezone;
private int _size;
private bool _ask;

public string LP
{
    get { return _lp; }
}

public int Size
{
    get { return _size; }
}

public string Timezone
{
    get { return _timezone; }
}

public bool Ask
{
    get { return _ask; }
}

public LiquidityBuilder(string lp, string timezone, int size, bool ask)
{
    _lp = lp;
    _timezone = timezone;
    _size = size;
    _ask = ask;
}
}

数据看起来像这样:

LP      Timezone      Size     Ask
GS       LDN        1000000  True
GS       LDN        3000000  True
GS       TOR        2000000  True
JPM      TOR        1000000  False
CS       ASIA       1000000  True
JPM      TOR        1000000  False
CITI     TOR        2000000  False

我需要计算具有键LP,时区和大小的组,例如 GS LDN True - >数:2

以下是我所拥有的:

var result = liquidtyTimezoneData.GroupBy(x => new { x.LP, x.Timezone, x.Ask })
                         .Select(x => new
                         {
                             LP = x.Key.LP,
                             Timezone = x.Key.Timezone,
                             Ask = x.Key.Ask,
                             Sum = x.Sum(z => z.Size)
                         });

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

只需使用x.Count()即可获得该组中的项目数。

答案 1 :(得分:0)

实施例

var result = liquidtyTimezoneData.GroupBy(x => new { x.LP, x.Timezone, x.Ask });
        foreach (var r in result)
        {
            Console.WriteLine("LP: {0} TZ: {1} Ask: {2} Count: {3}", r.Key.LP, r.Key.Timezone, r.Key.Ask, r.Count());
        }