Sort different types of data in an array of object in C#

২৬টি ভিউ
প্রথম অপঠিত মেসেজটিতে চলে আসুন

xlFAQ

পড়া হয়নি,
১৯ ফেব, ২০২৩, ১২:২২:৪৭ PM১৯/২/২৩
প্রাপক Excel-DNA
Hi friends,
With being a newbie in C# I seem to be unable find a way to sort a data array containing Numbers as well as Strings in an object[,] type of variable.
Code found till now, worth enough, is like:

        public static object fxlSort(
            object[,] MainRange,
            int KeyOrder)
        {
            return MainRange.OrderBy(f => f[KeyOrder - 1]);
        }

        public static T[,] OrderBy<T>(this T[,] source, Func<T[], T> keySelector)
        { return source.ConvertToSingleDimension().OrderBy(keySelector).ConvertToMultiDimensional(); }

        public static T[,] OrderByDescending<T>(this T[,] source, Func<T[], T> keySelector)
        { return source.ConvertToSingleDimension(). OrderByDescending(keySelector).ConvertToMultiDimensional(); }

        private static IEnumerable<T[]> ConvertToSingleDimension<T>(this T[,] source)
        {
            T[] arRow;

            for (int row = 0; row < source.GetLength(0); ++row)
            {
                arRow = new T[source.GetLength(1)];

                for (int col = 0; col < source.GetLength(1); ++col)
                    arRow[col] = source[row, col];

                yield return arRow;
            }
        }

        private static T[,] ConvertToMultiDimensional<T>(this IEnumerable<T[]> source)
        {
            T[,] twoDimensional; T[][] arrayOfArray; int numberofColumns;
            arrayOfArray = source.ToArray();
            numberofColumns = (arrayOfArray.Length > 0) ? arrayOfArray[0].Length : 0;
            twoDimensional = new T[arrayOfArray.Length, numberofColumns];
            for (int row = 0; row < arrayOfArray.GetLength(0); ++row)
                for (int col = 0; col < numberofColumns; ++col)
                    twoDimensional[row, col] = arrayOfArray[row][col];
            return twoDimensional;
        }


However, the same is found to be working only if the sorting filed, i.e. KeyOrder is of the same data type, but a #Value error if the data is of an object type containing numbers as well as text.

Kindly see if any of you experts can help in this regard.

Thanks in advance.
সকলকে উত্তর দিন
লেখককে লিখে পাঠান
ফরওয়ার্ড করুন
0টি নতুন মেসেজ