如何删除基于对象 属性 的两个列表 <object> 项之一?

How to remove one of two list<object> items based on an object property?

我有一个列表,其中包含相似但不同的项目 createdOn 日期。我只想保留显示名称相同但最新 createdOn 日期的项目。 我创建了一个谓词来比较基于 displayName 的列表项,因此我能够找到是否有具有相同 displayName 的项,但我不确定如何找到另一个具有旧 createdOn 的项日期并将其删除。

The predicate

public bool Equals(Obj x, Obj y)
        {
            if (x == null && y == null) { return true; }
            if (x == null || y == null) { return false; }

            return x.DisplayName == y.DisplayName;
        }

        public int GetHashCode(Obj obj)
        {
            if (obj == null || obj.DisplayName == null) { return 0; }
            return obj.DisplayName.GetHashCode();
        }

The RemoveDuplicateMethod:

public static List<Obj> RemoveDuplicatesSet(List<Obj> items, ValueComparer valueComparer)
    {
        // Use HashSet to maintain table of duplicates encountered.
        var result = new List<Obj>();
        var set = new HashSet<Obj>(valueComparer);
        for (int i = 0; i < items.Count; i++)
        {
            // If not duplicate, add to result.
            if (!set.Contains(items[i]))
            {
                result.Add(items[i]);
                // Record as a future duplicate.
                set.Add(items[i]);
            }
        }
        return result;
    }

有什么想法吗?

好吧,我会这样使用它:

List<Obj> items = items
    .GroupBy(x => x.Id) // or DisplayName, question is unclear
    .Select(g => g.OrderByDescending(x => x.CreatedOn).First())
    .ToList();

您也可以将您的比较器传递给 GroupBy,虽然我不知道 ValueComparer,如果它实现 IEqualityComparer<Obj> 就可以。

我不知道你有哪些数据,但请尝试使用 LINQ。

var dItems = items.Distinct();

如果您只想要最新的,请使用 lambda 表达式。

var dItems = items.OrderByDescending(x => x.createdOn).Distinct();