Domanda

Hello i do want a sort an array, that contains this:

String[] info = new String[5]{"6,j", "7,d", "12,s", "4,h", "14,s" };

But if i use this:

Array.Sort(info);

The output becomes:

"7,d"
"6,j"
"4,h"
"14,s"
"12,s"

But i wont the output to be:

"14,s"
"12,s"
"7,d"
"6,j"
"4,h"

What is the easiest way to do it in/with C#??

And i cant get Alphanumeric sort to work when i do like this:

Array.Sort(info, new AlphanumComparatorFast());

the type or namespace "AlphanumComparatorFast" could not be found are you missing a using directive or an assembly reference

is the error that i get...

È stato utile?

Soluzione

try with:

var sortedArray = info.OrderBy(s=>int.Parse(s.Split(',')[0])).ToArray();

This sorts just by the numeric part, but you can elaborate on that sample. This code strongly assumes that there is always the comma separator, this may be is an issue in production, do some more accurate error handling. Should the array contains some elements that does not conform the exception, providing that is acceptable to ignore the failing elements, we can write:

 var sortedArray = info.Where(k=>!string.IsNullOrEmpty(k)&&k.IndexOf(",")!=-1)
.OrderBy(s=>int.Parse(s.Split(',')[0])).ToArray();

Altri suggerimenti

Rather than represent these as strings, you could parse them and split them out into a class. Implement IComparable and you're sorted. Pun fully intended.

Or, implement your own sort comparator to parse the objects and then sort them correctly.

you can use a custom comparer

public class MyComparer : IComparer<string>
{
    public int Compare(string x, string y)
    {
        // return value greater than zero if x is greater than y
        // return zero if x is equal to y
        // return value less than zero if x is less than y
    }
}

and you can use your comparer like so

Array.Sort(info, new MyComparer());

If you're using .NET 2.0 and unable to use Linq you can try:

 String[] info = new String[5] { "6,j", "7,d", "12,s", "4,h", "14,s" };
            Array.Sort(info, delegate(string a, string b)
            {
                int numberA = int.Parse(a.Substring(0, a.IndexOf(',')));
                int numberB = int.Parse(b.Substring(0, b.IndexOf(',')));

                string stringA = a.Substring(a.IndexOf(','));
                string stringB = b.Substring(b.IndexOf(','));

                if (numberA > numberB) return -1;
                else if (numberA < numberB) return 1;
                else return stringA.CompareTo(stringB);
            }
                );

This assumes the separator is always a comma, add your own validation code if needed.

Here is a bit of code I wrote a while ago, I'm sure there's a more efficient way to do it, but this certainly works. To use it, include:

using System.Linq;

then call use a linq query:

Array.Sort(info,delegate(string x, string y){return NaturalCompare(y,x)}); sort as you seem to want

and of course include the relevant method:

    public int NaturalCompare(string x, string y)
    {
        string[] x1, y1;
        x1 = Regex.Split(x.Replace(" ", ""), "([0-9]+)");
        y1 = Regex.Split(y.Replace(" ", ""), "([0-9]+)");
        for (int i = 0; i < x1.Length && i < y1.Length; i++)
        {
            if (!x1[i].Equals(y1[i]))
            {
                return PartCompare(x1[i], y1[i]);
            }
        }
        return x.CompareTo(y);
    }

    private int PartCompare(string left, string right)
    {
        int x, y;
        if (int.TryParse(left, out x) && int.TryParse(right, out y))
            return x.CompareTo(y);
        return left.CompareTo(right);
    }

Sorting on the numeric part of the string:

var info = new String[5]{"6,j", "7,d", "12,s", "4,h", "14,s" };
foreach (var item in info.OrderByDescending (x => 
                                   int.Parse(x.Substring(0, x.IndexOf(',')))))
{
    Console.WriteLine(item);
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top