90abyss 90abyss - 1 year ago 63
C# Question

First group a list acc to a custom rule and later sort the group based on another field

I'm new to linq so please forgive my ignorance.

I've a list which I need to group based on a certain condition.

Now, my list contains 2 fields -

1) Type 2) Severity

My types are:

a) VM b) SQL c) LoadBalancer

My severity can be:

a) sev1 b) sev2 c) sev3

I want to group the list based on the following strict order: (so first LoadBalancer stuff should show - later VM - and finally SQL ones)

1) LoadBalancer 2) VM 3) SQL

And once they are grouped, I want to sort them based on severity.

I'm able to group it using a non-defined grouping mechanism here:

from i in thelist
group i by i.Type;

I was reading some material online and it looks like i will have to override equals and hash method.. I'm not sure how to do that? Or is there some better approach?


Answer Source

Since you did not specify what objects are on this list ("Now, my list contains 2 fields -" (?) ) I assumed it's (please tell me if anything is wrong):

class TestItem {
    public string type;
    public string severity;

And with a bit of LINQ

var test = list
    .OrderBy(i =>
        i.type.StartsWith("S") ? 3 :
        i.type.StartsWith("V") ? 2 : 1)
    .ThenBy(i => i.severity);

I know it's a bit of a hack, but it works for this weird type of sorting.

For the input:

new TestItem("VM", "sev1"),
new TestItem("SQL", "sev2"),
new TestItem("Load", "sev1"),
new TestItem("VM", "sev2"),
new TestItem("SQL", "sev1"),
new TestItem("Load", "sev2"),
new TestItem("SQL", "sev3")

Output (properties):

"Load", "sev1"
"Load", "sev2"
"VM", "sev1"
"VM", "sev2"
"SQL", "sev1"
"SQL", "sev2"
"SQL", "sev3"