按计数对象分组

本文关键字:对象 | 更新日期: 2023-09-27 18:33:56

我想计算我分组的项目数。我有一个类型为流动性生成器的列表:

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 真 --> 计数: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)
                         });

有什么建议吗?

按计数对象分组

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

示例

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());
        }