Returns a separate list of an array of objects where the number of elements in the array is not specific

Is there a way to use LINQ to get a separate list of elements from a list of an array of objects without knowing how many elements exist in each array? The number of elements in each element of the array will be the same throughout the list.

        // 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?

I know how many elements are there at runtime, if that helps?

If this is not possible in LINQ, can someone suggest a method that I could use to achieve the desired results?

+4
source share
2 answers

If I understand you correctly, you can try something like this:

   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
*/
        }
+3
source

,

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();

-1

All Articles