-3

Input: list of lists of two integers

List<List<int>> lists = new List<List<int>>() {
  {1,2},
  {20,21},
  {3,2},
  {21,55}
};

output: list of lists of two integers which have the same first OR second integer value

{
  {{1,2}, {3,2}}, 
  {{20,21}, {21,55}}
}
  • 3
    [ask], and [mre] would have been nice. _"list of lists of two integers"_? Is those 2 integer a Tuple? and array? A keypair? An object with 2 properties? Do you have the initilisation of a smallest sample. And the expected result. Do you want to group in place in the nested nested . or flattern? – Self Apr 16 '21 at 07:01
  • Please, provide an *example* of both *input* and the expected *result* – Dmitry Bychenko Apr 16 '21 at 07:09
  • Ok so if the inner element is a list are you sure there is alway 2 element for the group by ? May there be more? may there be less?Or do you need to guard against that – Self Apr 16 '21 at 07:13
  • What is the expected answer for `{{1, 2}, {3, 2}, {2, 5}}`, please? – Dmitry Bychenko Apr 16 '21 at 07:20
  • the same {{1, 2}, {3, 2}, {2, 5}} – Hossam Moussa Apr 16 '21 at 07:21
  • Select the first two elements of inner list using Take(2), and compare them with Any()/Contains(). – Self Apr 16 '21 at 07:23
  • Does this answer your question? [writing a custom comparer for linq groupby](https://stackoverflow.com/questions/37733773/writing-a-custom-comparer-for-linq-groupby) – Self Apr 16 '21 at 07:29

1 Answers1

1

https://dotnetfiddle.net/Udb15e As stated in writing a custom comparer for linq groupby, When writing your own IEqualityComparer, you have to implement Equals and GetHashCode.
But GetHashCode will be called first and if they are different Equals will not be called.
So we need to force GetHashCode to a constant.

// https://stackoverflow.com/questions/5231845/c-sharp-linq-group-by-on-multiple-columns
class ListFirstTwoComparer : IEqualityComparer<List<int>>
{
    public bool Equals(List<int> a, List<int> b)
    {
        var a2 = a.Take(2);
        var b2 = b.Take(2);

        //https://stackoverflow.com/questions/11092930/check-if-listt-contains-any-of-another-list
        return  a2.Any(x => b2.Any(y => y == x));
    }

    public int GetHashCode(List<int> input)
    {
        return 0;       
    }
}

var result = lists.GroupBy(p => p, new ListFirstTwoComparer());

Result :

[
    {    
        {1,2},
        {1,2},
        {3,2}        
    },
    {        
        {20,21},
        {21,22}        
    }
]
Self
  • 349
  • 1
  • 8