0

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.

Luki
  • 39
  • 5
  • 1
    Grouping by strings is case sensitive. Are you sure all strings have the same casing? – Flat Eric Mar 19 '19 at 14:21
  • 1
    Possible duplicate of [Select distinct using linq](https://stackoverflow.com/questions/19406242/select-distinct-using-linq) – Luthando Ntsekwa Mar 19 '19 at 14:21
  • The code posted only removes duplicate names and not other properties. It also does remove items spelled differently or uses different Upper/Lowercase letters. – jdweng Mar 19 '19 at 14:29
  • I tried with `g.Name.ToUpper()` to eliminate case-sensivity issues, but still no success. Is there any way to achieve this using linq, and without using iteration/loops? – Luki Mar 19 '19 at 14:38
  • Can you add an example of what your `List` data looks like that you are trying to query? – Stemado Mar 19 '19 at 15:16
  • I am working on a plugin for a software - Autodesk Revit. Here is a documentation for the class: http://www.revitapidocs.com/2015/65dc0795-6495-74c0-92b6-267a18ce4d4e.htm – Luki Mar 19 '19 at 15:33

2 Answers2

1

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));
NetMage
  • 26,163
  • 3
  • 34
  • 55
0

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
LiefLayer
  • 977
  • 1
  • 12
  • 29