0

I have found many linq posts on here that group an object by a field but i haven't found a way to group an object by numerous fields.

Lets say i have an object like the following:

class Obj
{
    public string field1 {get;set;}
    public string field2 {get;set;}
    public string field3 {get;set;}
}

Then i have a list of objects like:

List<Obj> ol = new List<Obj>

Obj obj = new Obj();
obj.field1 = "a1";
obj.field2 = "a2";
obj.field3 = "a3";
ol.Add(obj);

obj.field1 = "a4";
obj.field2 = "a5";
obj.field3 = "a6";
ol.Add(obj);

obj.field1 = "a7";
obj.field2 = "a8";
obj.field3 = "a9";
ol.Add(obj);

obj.field1 = "a1";
obj.field2 = "a2";
obj.field3 = "a3";
ol.Add(obj);

So now there is a list of four objects. What i want is to group the list by all three fields. I know how to group the list by 1 field but i have not had any luck when grouping by multiple fields. So the result i am looking for is a list of three since fields 1,2, and 3 are the same in two of the objects.

To group by one field i have done the following which works fine:

var grouped = obj.GroupBy(u => u.field1);

What i am looking for is something like the following which is invalid syntax but it's one of the things i have tried:

var grouped = obj.GroupBy(u => u.field1 && v => v.field2 && w => w.field3);

The idea would be the same thing in sql if you were grouping by multiple fields like:

select * from foo group by field1, field2, field3

Thanks in advance for any help

Maxqueue
  • 1,309
  • 1
  • 12
  • 35

1 Answers1

1

If I have understood what you are trying to do correctly, you could try:

var grouped = obj.GroupBy(u => new { u.field1, u.field2, u.field3 })
stybl
  • 8,580
  • 3
  • 24
  • 48