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

时间:2014-09-17 08:58:47

标签: c# linq distinct

有没有办法使用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中无法实现,那么有人可以建议一种我可以用来达到预期效果的方法吗?

2 个答案:

答案 0 :(得分:3)

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

   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
*/
        }

答案 1 :(得分:-1)

请尝试使用以下代码

List<object[]> bar  = foo.GroupBy(x => new { X1 = x[0], X2 = x[1], X3 = x[2] }).Select(g => new object[] { g.Key.X1, g.Key.X2, g.Key.X3, g.Count() }).ToList();

每个对象有四个值,最后一个用于计数组