从列表中删除了对象属性重复

时间:2013-11-10 15:26:18

标签: c#

这是我的目标:

public class MyObject
{
    public int id { get; set; }
    public string fileName { get; set; }
    public string browser { get; set; }    
    public string protocol { get; set; }    
    public string family { get; set; }
}

我有一个我的对象列表:

List<Capture> list = db.Captures.Where(x => x.family == "Web").ToList();

我想要做的是获取删除重复protocol的新列表。 例如,如果我在我的列表中有10个对象,其中9个具有协议DOC和1 PDF我想要一个只有2个对象DOC和1 PDF <的新列表/ p>

4 个答案:

答案 0 :(得分:1)

有几种方法可以执行此操作,具体取决于您通常希望如何使用MyObject类的实例。

最简单的方法是实施IEquatable<T> interface,以便仅比较protocol字段:

public class MyObject : IEquatable<MyObject>
{
    public sealed override bool Equals(object other)
    {
        return Equals(other as MyObject);
    }

    public bool Equals(MyObject other)
    {
        if (other == null) {
            return false;
        } else {
            return this.protocol == other.protocol;
        }
    }

    public override int GetHashCode()
    {
        return protocol.GetHashCode();
    }
}

然后,您可以在将可枚举转换为列表之前调用Distinct


或者,您可以使用Distinct overloadIEqualityComparer

相等比较器必须是一个根据您的标准确定相等性的对象,在问题中描述的情况下,通过查看protocol字段:

public class MyObjectEqualityComparer : IEqualityComparer<MyObject>
{
    public bool Equals(MyObject x, MyObject y)
    {
        if (x == null) {
            return y == null;
        } else {
            if (y == null) {
                return false;
            } else {
                return x.protocol == y.protocol;
            }
        }
    }

    public int GetHashCode(MyObject obj)
    {
        if (obj == null) {
            throw new ArgumentNullException("obj");
        }

        return obj.protocol.GetHashCode();
    }
}

答案 1 :(得分:1)

我认为这是最简单的方法:以下内容将list分组为protocol,然后从每个组中获取第一个实例以生成一个枚举,其中包含每种类型{{1}的一个实例}。

protocol

答案 2 :(得分:0)

选择不同的协议,循环它们并仅选择相同协议的第一个对象 - 这样您就可以获得所需的列表。

答案 3 :(得分:0)

您可以使用Distinct,也可以使用此处提供的相同解决方案:

Distinct() with lambda?