Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ GroupBy collection

Is it possible to GroupBy in LINQ, using a collection property?

e.g.

void Main()
{
    var t1 = new Test() { Children = new List<string>() { "one", "two" } };
    var t2 = new Test() { Children = new List<string>() { "one", "two" } };
    var t3 = new Test() { Children = new List<string>() { "one", "three" }        };

    var tests = new List<Test>() { t1, t2, t3 };
    var anon =  from t in tests
                select new
                {
                    Children = t.Children
                };

    anon.GroupBy(t => t.Children).Dump();
}

public class Test
{
    public List<string> Children {get;set;}
}

In this example, I would hope for two groups:

Key: List() { "one", "two" } Value: t1, t2

Key: List() { "one", "three" } Value: t3

My understanding is that anonymous types are compared not by reference, but by comparing equality on their public properties.

However, the actual result is three groups:

Key: List() { "one", "two" } Value: t1

Key: List() { "one", "two" } Value: t2

Key: List() { "one", "three" } Value: t3

If this is not possible, is there a way to get the result I want?

Hopefully explained this clearly...

like image 898
TheNextman Avatar asked Nov 15 '11 15:11

TheNextman


1 Answers

By default, GroupBy is going to use reference equality when grouping by lists (which are reference types).

Since you've got new instances of the list each time, they are not equal.

However, there is an overload of GroupBy which lets you specify a custom IEqualityComparer, so that you can implement your own way of comparing a list of strings, for example.

To implement this, there are many other threads here about comparing two lists.

like image 166
wsanville Avatar answered Sep 28 '22 12:09

wsanville