c# – 返回对象数组的不同列表,其中数组项的数量是非特定的

有没有办法使用LINQ从对象数组列表中获取不同的项目列表,而不知道每个数组中有多少项?每个数组项中的项数在整个列表中都是相同的.

        // Foo is a list of object arrays. The number of items
        // each array is non-specific.
        // (In this example there is only 3 items, but there could be 100)
        var foo = new List<object[]>();

        // I add some items to the list.
        foo.Add(new object[] { 1, "Something", true });
        foo.Add(new object[] { 1, "Some Other", false });
        foo.Add(new object[] { 2, "Something", false });
        foo.Add(new object[] { 2, "Something", false });

        // This will get me a distinct list from the array list...
        // but it requires I know how many items are in each array.
        List<object[]> bar = foo.Select(x => new { X1 = x[0], X2 = x[1], X3 = x[2] })
                                 .Distinct()
                                 .Select(x => new object[] { x.X1, x.X2, x.X3 })
                                 .ToList();



        List<object[]> bar = ?? /// < -- How can I rewrite the
        //                                 previous line so that
        //                                 my code works with n array items?

如果有帮助,我会知道运行时有多少项?

如果在LINQ中不可能,那么有人可以建议我可以用来实现预期结果的方法吗?

最佳答案 如果我理解你,你可以尝试这样的事情:

   class Comparer : IEqualityComparer<object[]>
        {
            public bool Equals(object[] x, object[] y)
            {
                if (x.Length != y.Length)
                    return false;

                for (int i = 0; i < x.Length; ++i)
                    if (!x[i].Equals(y[i]))
                        return false;

                    return true;
                }

                public int GetHashCode(object[] obj)
                {
                    return string.Join("", obj).GetHashCode();
                }
        }

     static void Main(string[] args)
        {
            var foo = new List<object[]>();

            foo.Add(new object[] { 1, "Something", true });
            foo.Add(new object[] { 1, "Some Other", false });
            foo.Add(new object[] { 2, "Something", false });
            foo.Add(new object[] { 2, "Something", false });

            var distinctList = foo.Distinct(new Comparer()).ToList();
/*
distinctList now contains
1, "Something", true
1, "Some Other", false
2, "Something", false
*/
        }
点赞