kknaguib
kknaguib

Reputation: 749

Group by multiple items in list then sum and average c#

I need to perform quite a complicated query and having difficulty doing it. what I have is a list of objects called 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;
    }
}

The data will look something like this:

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

I'm first trying to group by the "LP" then by "Timezone" then by "Ask" then sum the sizes. So example,

GS     (Ask)
LDN: 4000000
TOR: 2000000

This is what I have:

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

now I can't group by string's what would also be the most efficient way to do this because performance matters for the application I'm developing..Any suggestions? Thanks!

Upvotes: 2

Views: 2404

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21825

For getting the sum, as per your comment you can try this:-

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

Then simply iterate it with a foreach loop:-

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

I am getting following output:-

enter image description here

Upvotes: 3

Related Questions