Reputation: 39
How to get unique elements from the list based on Property string Name
?
I have tried this, but it doesn't work. Resulting List is sorted and grouped, but duplicated elements are not removed:
List<ElementType> uniqueTypes = types.OrderBy(g => g.Name)
.GroupBy(g => g.Name).Select(s => s.First()).ToList();
Any help, much appreciated.
Upvotes: 0
Views: 244
Reputation: 26917
Use one of the standard definitions for the extension method DistinctBy
. Here are a couple I use:
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, IEqualityComparer<TKey> comparer = null) {
var seenKeys = new HashSet<TKey>(comparer);
foreach (var e in src)
if (seenKeys.Add(keySelector(e)))
yield return e;
}
public static IEnumerable<T> DistinctBy<T, TKey>(this IEnumerable<T> src, Func<T, TKey> keySelector, Func<IGrouping<TKey, T>, T> pickOne, IEqualityComparer<TKey> comparer = null) =>
src.GroupBy(keySelector).Select(g => pickOne(g));
Upvotes: 1
Reputation: 1073
A solution would be to create a copy of your List and implement Equals and GetHashCode in your ElementType (you can implement Equals so that it return true when only properties name are equals) so that you can add to your new list only elements that are not in your old list by using:
if (newList.Contains(element))
//remove element from the old list or you can check if !Contains and add the element to the new list
Upvotes: 0