I have a list which has items that are similar but have different createdOn
dates. I want to only keep the items with same displayName but the latest createdOn
date. 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.
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;
}
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.
I don't know the data you have but try using LINQ.
var dItems = items.Distinct();
And if you want only lastest ones use lambda expression.
var dItems = items.OrderByDescending(x => x.createdOn).Distinct();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.