开发者

Sorting from Alphanumeric to nonAlphnumeric

I have a array of data:

!
A
B
E
$
N

I'd like it to be sorted from Alphanumeric to Non-Alphanumeric.

Example: A B E N !开发者_开发百科 $

How would I go about accomplishing this?


char[] yourOriginalValues = new [] { '!', 'A', 'B', 'E', '$', 'N' };

IEnumerable<char> result = 
       yourOriginalValues.Where(c => Char.IsLetterOrDigit(c))
            .OrderBy(c => c)
            .Concat(yourOriginalValues.Where(c => !Char.IsLetterOrDigit(c)));

That seems to yield the values you're looking for.


This can be achieved with a combination of the OrderBy and ThenBy extension methods:

char[] data = { 'E', 'B', '$', 'N', '!', 'A' };
var query = data.OrderByDescending(c => char.IsLetter(c))
                .ThenBy(c => c);


If you want to have a customized sorting order, you need to provide your own comparison function. In your case (letters+digits first, the rest later), you can use something like

var data = "!ABE$N".ToCharArray().ToList();
data.Sort((x, y) => {
    if (x == y) return 0;
    if (Char.IsLetterOrDigit(x))
    {
        if (!Char.IsLetterOrDigit(y)) return -1;
        return x < y ? -1 : +1;
    }
    else
    {
        if (Char.IsLetterOrDigit(y)) return +1;
        return x < y ? -1 : +1;
    }
});

Added per comment: The same thing, only with a different syntax (using a plain-old named method):

int MyComparisonFunction(char x, char y)
{
    if (x == y) return 0;
    if (Char.IsLetterOrDigit(x))
    {
        if (!Char.IsLetterOrDigit(y)) return -1;
        return x < y ? -1 : +1;
    }
    else
    {
        if (Char.IsLetterOrDigit(y)) return +1;
        return x < y ? -1 : +1;
    }
}

// ...

var data = "!ABE$N".ToCharArray().ToList();
data.Sort(MyComparisonFunction);

The same thing in still another style would be to create an IComparer implementation and use that. That is useful if the sorting order should be used on more places, many collections and controls offer an IComparer property to override the sorting order:

public class AlphabeticPriorToNonalphabeticComparer : IComparer<char>
{
    public int Compare(char x, char y)
    {
        if (x == y) return 0;
        if (Char.IsLetterOrDigit(x))
        {
            if (!Char.IsLetterOrDigit(y)) return -1;
            return x < y ? -1 : +1;
        }
        else
        {
            if (Char.IsLetterOrDigit(y)) return +1;
            return x < y ? -1 : +1;
        }
    }
}
// ...
var data = "!ABE$N".ToCharArray().ToList();
var myComparer = new AlphabeticPriorToNonalphabeticComparer();
data.Sort(myComparer);


myArray.Sort();

That will use the default, alphabetic (non numeric) sort. That should work or am I missing something?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜