2

我有一门课如下

class WarningClass
    {
        public string SqlEyeWarning { get; set; }
        public string FileName { get; set; }
    }

它的填充如下

List<WarningClass> lstWarningClass1 = new List<WarningClass>();
lstWarningClass1.Add(new WarningClass { FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." });
lstWarningClass1.Add(new WarningClass { FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." });
lstWarningClass1.Add(new WarningClass { FileName = "c.sql", SqlEyeWarning = "SD009: Missing or order mismatch of Grant statement." });

可以看出,第一条和第二条记录存在重复条目。

如何获得唯一条目。

最终输出

FileName = "a.sql", SqlEyeWarning = "SD001: order mismatch or it should be ON." 
FileName = "c.sql", SqlEyeWarning = "SD009: Missing or order mismatch of Grant statement."

如果我这样做lstWarningClass1.Distinct(),那是行不通的

4

3 回答 3

3

Linq 的 Distinct() 的描述如下:

默认相等比较器 Default 用于比较实现IEquatable 泛型接口的类型的值。要比较自定义数据类型,您需要实现此接口并为该类型提供您自己的 GetHashCode 和 Equals 方法。

做粗体部分, Distinct() 将起作用。

于 2013-06-06T02:44:21.110 回答
1

您可以使用IEnumerable.GroupBy您关心的标准对列表中的对象进行分组。然后,您可以选择每个组的第一个元素。

你可以FileName这样分组:

lstWarningClass1.GroupBy(w => w.FileName).Select(g => g.First())

或者像FileName这样SqlEyeWarning

lstWarningClass1.GroupBy(w => new {w.FileName, w.SqlEyeWarning}).Select(g => g.First())

于 2013-06-06T02:43:51.657 回答
1

您需要创建一个自定义IEqualityComparer<T>

public class CustomComparer : IEqualityComparer<WarningClass>
{
    public bool Equals(WarningClass x, WarningClass y)
    {
        return x.SqlEyeWarning.Equals(y.SqlEyeWarning)
               && x.FileName.Equals(y.FileName);
    }

    public int GetHashCode(WarningClass obj)
    {
        return obj.FileName.GetHashCode() 
            ^ obj.SqlEyeWarning.GetHashCode();
    }
}

然后使用您的自定义比较器调用重载Distinct方法:

var result = lstWarningClass1.Distinct(new CustomComparer());
于 2013-06-06T03:18:22.520 回答