【问题标题】:How to remove one of two list<object> items based on an object property?如何根据对象属性删除两个 list<object> 项目之一?
【发布时间】:2018-11-27 12:04:42
【问题描述】:

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

谓词

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

RemoveDuplicate 方法:

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

有什么想法吗?

【问题讨论】:

  • 旁注:你不需要检查HashSet是否包含它,只需Add它。如果不包含则添加,如果可以添加则返回true
  • 按标识符分组,按日期降序对组进行排序,并为每个组取第一项
  • 什么是“谓词”EqualsGetHashCode 在哪里?你也说你用Id比较,但你用DisplayName比较。
  • 我会改的。我的意思是显示名称,我想保持谨慎。 :)
  • 了解 IEqualityComparer

标签: c# asp.net asp.net-web-api c#-4.0


【解决方案1】:

好吧,我会这样使用它:

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&lt;Obj&gt;,它就可以工作。

【讨论】:

    【解决方案2】:

    我不知道您拥有的数据,但请尝试使用 LINQ。

    var dItems = items.Distinct();
    

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

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

    【讨论】:

    • 这可能不起作用,因为 Distinct 也会考虑 CreatedOn 字段。因此,您最终会得到具有不同 CreatedOn 字段的重复 ID。
    • 你是 100% 正确的。那么也许var items = items.GroupBy(x =&gt; x.Id).OrderByDescending(g =&gt; g.createdOn).Select(group =&gt; group.First());
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-02
    • 2019-08-03
    • 2019-03-24
    • 1970-01-01
    • 2019-06-23
    • 2015-08-31
    相关资源
    最近更新 更多