【问题标题】:How to remove duplicate tests with duplicate outcomes using C#?如何使用 C# 删除具有重复结果的重复测试?
【发布时间】:2016-04-06 14:38:00
【问题描述】:

所以我有一个很大的列表,其中包含最多可能运行 3 次的测试,并且可能有 2 次相同的消息,第三次它可能具有与前两次运行不同的消息。我正在尝试实现一个代码,它只显示独特的测试,并具有独特的结果。 为了更好地观察,这将是一个用例:

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

如您所见,“TestABC”出现 2 次,出现相同错误,出现 1 次出现不同错误。我想在过滤后看到以下输出:

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

我对 C# 还是很陌生,如果有任何帮助或指导,我将不胜感激。 谢谢!

【问题讨论】:

标签: c# linq sorting distinct trx


【解决方案1】:

首先你要实现IEqualityComparer接口并使用Distinct方法

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;
    }
}

如果你使用List 使用Distinct 方法

testList.Distinct(new Comparer())

但我建议使用Set 和IEqualityComparer。

【讨论】:

    猜你喜欢
    • 2020-02-04
    • 2017-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-06-19
    • 2022-07-06
    • 1970-01-01
    • 2014-08-02
    • 1970-01-01
    相关资源
    最近更新 更多