如何使用LINQ从数组列表中检索一组唯一数组?

Myk*_*lik 5 c# linq arrays list

我有这样的结构

List<int[]> propIDs = new List<int[]>();
Run Code Online (Sandbox Code Playgroud)

我可以使用LINQ从propID获取所有唯一值.例如,我有(1,2)(4,5)(1,5)(1,2)(1,5)的列表,我必须得到(1,2) )(4,5)(1,5)

Mik*_*oud 1

以下是满足您需求的完整且有效的应用程序。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ListsAndArrays
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int[]> propIDs = new List<int[]>();
            propIDs.Add(new[] { 1, 2 });
            propIDs.Add(new[] { 4, 5 });
            propIDs.Add(new[] { 1, 5 });
            propIDs.Add(new[] { 1, 2 });
            propIDs.Add(new[] { 1, 5 });

            var distinct = propIDs.Distinct(new DistinctIntegerArrayComparer());

            foreach (var item in distinct)
            {
                Console.WriteLine("{0}|{1}", item[0], item[1]);
            }

            if (Debugger.IsAttached)
            {
                Console.ReadLine();
            }
        }

        private class DistinctIntegerArrayComparer : IEqualityComparer<int[]>
        {
            public bool Equals(int[] x, int[] y)
            {
                if (x.Length != y.Length) { return false; }
                else if (x.Length != 2 || y.Length != 2) { return false; }

                return x[0] == y[0] && x[1] == y[1];
            }

            public int GetHashCode(int[] obj)
            {
                return -1;
            }
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

  • 虽然这可行,但返回常量(此处为“-1”)哈希码是最糟糕的(仍然正确)实现。 (2认同)