[英]How to remove one of two list<object> items based on an object property?
I have a list which has items that are similar but have different createdOn
dates. 我有一个列表,其中包含类似但具有不同的createdOn
日期的项目。 I want to only keep the items with same displayName but the latest createdOn
date. 我只想保留具有相同displayName但最新的createdOn
日期的项目。 I have created a predicate to compare list items based on displayName, so I'm able to find if I have an item with the same displayName, but I'm not sure how do I find the other item with older createdOn
date and remove it. 我创建了一个谓词来比较基于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: 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;
}
Any ideas? 有任何想法吗?
Well, i'd use it in this way: 好吧,我会以这种方式使用它:
List<Obj> items = items
.GroupBy(x => x.Id) // or DisplayName, question is unclear
.Select(g => g.OrderByDescending(x => x.CreatedOn).First())
.ToList();
You could also pass your comparer to GroupBy
, although i don't know ValueComparer
, if it implements IEqualityComparer<Obj>
it works. 您也可以将比较器传递给GroupBy
,尽管我不知道ValueComparer
,如果它实现IEqualityComparer<Obj>
则可以正常工作。
I don't know the data you have but try using LINQ. 我不知道您拥有的数据,但尝试使用LINQ。
var dItems = items.Distinct();
And if you want only lastest ones use lambda expression. 如果只希望最新的代码,请使用lambda表达式。
var dItems = items.OrderByDescending(x => x.createdOn).Distinct();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.