从子List <int> </int>中删除重复的对象

时间:2015-03-27 09:16:28

标签: c# linq duplicates

我有一个类项目,想要删除重复项

public class Items
        {
            public List<int> Parts { get; set; }
            public int Total { get; set; }
        }

这里有样本数据:

List<Items> items = new List<Items>()
            {
                new Items(){ Parts = new List<int> { 6, 4, 0, 2, 0 }, Total = 100},
                new Items(){ Parts = new List<int> { 6, 4, 0, 2, 0 }, Total = 100},
                new Items(){ Parts = new List<int> { 1, 5, 0, 7, 3, 2 }, Total = 80},
                new Items(){ Parts = new List<int> { 1, 5, 0, 7, 3, 2 }, Total = 80},
                new Items(){ Parts = new List<int> { 1, 0, 4, 1 }, Total = 64},
                new Items(){ Parts = new List<int> { 3, 4, 0, 0, 2, 1 }, Total = 125},
                new Items(){ Parts = new List<int> { 3, 4, 0, 0, 2, 1 }, Total = 125},
                new Items(){ Parts = new List<int> { 2, 0, 1 }, Total = 26}
            };
        }

如何使用Linq删除列表中的重复项?

1 个答案:

答案 0 :(得分:4)

您可以使用Distinct()命名空间中的System.Linq方法。但是,首先它现在必须如何比较您的自定义对象实例。为此,您可以实现IEquatable<T> interface:

public class Items : IEquatable<Items>
{
    public int Total { get; set; }
    public List<int> Parts { get; set; }

    public bool Equals(Items other)
    {
        if (Total == other.Total && Parts.SequenceEqual(other.Parts))
            return true;

        return false;
    }

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

然后:

items = items.Distinct().ToList();