Delete duplicates in a List of int arrays

前端 未结 8 1217
我寻月下人不归
我寻月下人不归 2020-12-30 00:25

having a List of int arrays like:

List intArrList = new List();
intArrList.Add(new int[3] { 0, 0, 0 });
intArrList.Add(new int[5] {         


        
8条回答
  •  盖世英雄少女心
    2020-12-30 01:14

    Using MoreLINQ this can be very simple with DistinctBy.

    var result = intArrList.DistinctBy(x => string.Join(",", x));
    

    Similar to the GroupBy answer if you want distinction to be irrespective of order just order in the join.

    var result = intArrList.DistinctBy(x => string.Join(",", x.OrderBy(y => y)));
    

    EDIT: This is how it's implemented

    public static IEnumerable DistinctBy(this IEnumerable source,
                Func keySelector, IEqualityComparer comparer)
            {
                if (source == null) throw new ArgumentNullException(nameof(source));
                if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
    
                return _(); IEnumerable _()
                {
                    var knownKeys = new HashSet(comparer);
                    foreach (var element in source)
                    {
                        if (knownKeys.Add(keySelector(element)))
                            yield return element;
                    }
                }
            }
    

    So you if you don't need MoreLINQ for anything else you can just use a method like this:

    private static IEnumerable GetUniqueArrays(IEnumerable source)
        {
            var knownKeys = new HashSet();
            foreach (var element in source)
            {
                if (knownKeys.Add(string.Join(",", element)))
                    yield return element;
            }
        }
    

提交回复
热议问题