class Foo()
{
public Bar [] bars;
}
class Bar ()
{
public string name;
public int id;
}
I have an IEnumerable<Foo> and I want to construct an IEnumerable<Bar> which contains which contains every unique bar (and ordered by ID…but I can handle that part on my own).
I feel that this is the type of task that LINQ is made for..but I can’t seem to figure out how to make it happen.
As an example, if I had:
foo[0] => bars { { name = "one", id = 1 }, { name = "two", id = 2 }, { name = "three", id = 3 },
foo[1] => bars { { name = "four", id = 4 }, { name = "four", id = 4 }
I would want my linq statement to return:
{ name = "one", id = 1 }, { name = "two", id = 2 }, { name = "three", id = 3 }, { name = "four", id = 4 }
If your
Barclass overrodeEqualsandGetHashCode, it would be very simple:Without that equality implementation, you’ll need to create your own
IEqualityComparer<Foo>to pass into theDistinctmethod.If you only need to care about the
idto make them distinct, you could useDistinctByfrom MoreLINQ to make your life simpler:Or you could use an anonymous type as a quick hack to get an equality comparer across both values, still with MoreLINQ:
It would almost certainly be better to implement equality in
Barthough 🙂