-1

So I have a big list with tests that possibly are run maximum 3 times, and possibly have the same message 2 times, and the third time it could have a distinct message than the previous two runs. I am trying to implement a code that will show only unique tests, with unique outcomes. To have a better view, this would be a use case:

testname="TestABC" errormessage="ErrXYZ"
testname="Test3454" errormessage="Err123"
testname="TestABC" errormessage="Err123"
testname="TestABC" errormessage="ErrXYZ"
testname="Test3454" errormessage="ErrYTR"
testname="Test3454" errormessage="ErrABC"

As you can see, "TestABC" appears 2 times with the same error, and one time with a different error. I would like to see the following output after the filtering:

testname="TestABC" errormessage="ErrXYZ"
testname="Test3454" errormessage="Err123"
testname="TestABC" errormessage="Err123"
testname="Test3454" errormessage="ErrYTR"
testname="Test3454" errormessage="ErrABC"

I am quite new to C#, and would appreciate any help or guidance. Thanks!

1 Answers1

0

First of all, you have to implement IEqualityComparer interface and use Distinct method

class Comparer : IEqualityComparer<Test>
{
    public bool Equals(Test x, Test y)
    {
        return string.Equals(x.testname, y.testname) && string.Equals(x.errormessage, y.errormessage);
    }

    public int GetHashCode(Test obj)
    {
        string name = string.Format ("{0}{1}", obj.testname, obj.errormessage);
        int hash = 7;
        for (int i = 0; i < name.Length; i++)
        {
            hash = hash * 31 + name[i];
        }

        return hash;
    }
}

And if you use List use Distinct method

testList.Distinct(new Comparer())

But I suggest to use Set with the IEqualityComparer.

Valentin
  • 5,380
  • 2
  • 24
  • 38