1

I am trying to write a linq query which would give me this type of result

enter image description here

So I am trying to Group by order type which could be Surplus or Deficit. After that I am Grouping by Region and then I want to see how much of deficit of each masstype is there. So far I have achieved this

var results = Order.GetActive().GroupBy(x => x.OrderType).
        Select(i => new { OrderType = i.Key, Orders = i.ToList().GroupBy(j => j.GetLocation().Region) });

Now I am stuck in trying to group it by masstype and then calculate total amount. For example if there are 10 surplus orders for masstype1 I want to show one entry accumulating the amount.

Something like this

{
'Region'{

    'Oslo'{

        'Masstype' {

            'Rock' {

                'Defict', 100
                'Surplus', 0
            },
            'Mud' {

                'Defict', 100
                'Surplus', 100
            }
        }
    }
}
}

1 Answer 1

1

From the question, it is difficult to know what format you want the output to be in, however, you can group by multiple properties using an anonymous type like this:

var groupedEntries = Order.GetActive().GroupBy(x => new {x.OrderType, x.GetLocation().Region, x.MassType})

EDIT: Following the update, it looks like you want a structure something like this: Dictionary<string, Dictionary<string, Dictionary<string, int>>> which you can achieve with the following LINQ statement, however, at this point, I would recommend creating a new structure to hold this data:

var result = Order.GetActive()
    .GroupBy(a => a.OrderType)
    .ToDictionary(a => a.Key, a => a
        .GroupBy(b => b.GetLocation().Region)
        .ToDictionary(b => b.Key, b => b.
            GroupBy(c => c.MassType)
            .ToDictionary(c => c.Key, c => c.Sum(d => d.Value))
        )
    );
Sign up to request clarification or add additional context in comments.

9 Comments

What I am trying to get is a list containing regions and each region has a list of mass-types with total amount. And all of this divided into deficit and surplus which are order types. hope this explains.
I'm afraid it still isn't clear to me what the type of that object would be, maybe you could update the question with how you will use it?
I added a data structure of how I think the end object would look like.
If this doesn't help, maybe we can take it to private chat. :)
Thanks mate, I would try this and see if it works, ;)
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.