按列表中的多个项目分组然后求和和平均c#

时间:2014-12-10 17:41:13

标签: c# linq list group-by

我需要执行相当复杂的查询并且难以执行此操作。我所拥有的是一个名为LiquidityBuilder的对象列表:

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”分组,然后按“Timezone”分组,然后按“Ask”分组,然后将大小相加。例如,

GS     (Ask)
LDN: 4000000
TOR: 2000000

这就是我所拥有的:

var groupedLiquidityList = liquidtyTimezoneData
    .GroupBy(u => u.LP && u.Timezone && u.Ask)
    .Select(grp => grp.ToList())
    .ToList();

现在我不能按字符串分组,这也是最有效的方法,因为性能对我正在开发的应用程序很重要。有什么建议吗?谢谢!

1 个答案:

答案 0 :(得分:3)

要获得总和,根据您的评论,您可以尝试: -

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

然后简单地用foreach循环迭代它: -

foreach (var item in result)
{
   Console.WriteLine("LP: {0}, Timezone: {1}, Ask : {2}, Sum : {3}",item.LP,item.Timezone,item.Ask,item.Sum);
}

我得到以下输出: -

enter image description here