[英]How to get subset of List<T> items based on their Sum of an object property
[英]How to remove one of two list<object> items based on an object property?
我有一个列表,其中包含类似但具有不同的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();
}
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.