C# 用数字对数组列表进行排序

发布于 2024-12-27 11:05:11 字数 566 浏览 1 评论 0原文

你好,我确实想要对一个数组进行排序,其中包含这个:

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

但是如果我使用这个:

Array.Sort(info);

输出变成:

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

但我不会输出是:

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

在/使用 C# 中执行此操作的最简单方法是什么?

当我这样做时,我无法让字母数字排序工作:

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

找不到类型或命名空间“AlphanumComparatorFast” 您缺少 using 指令或程序集引用 ...

我得到的错误是

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...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

青巷忧颜 2025-01-03 11:05:11

尝试:

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

这仅按数字部分排序,但您可以详细说明该示例。此代码强烈假设始终存在逗号分隔符,这可能是生产中的问题,请进行一些更准确的错误处理。
如果数组包含一些不符合异常的元素,只要可以忽略失败的元素,我们可以编写:

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

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();
哀由 2025-01-03 11:05:11

您可以解析它们并将它们分成一个类,而不是将它们表示为字符串。实施 IComparable 就可以了。双关语完全是有意的。

或者,实现您自己的排序比较器来解析对象,然后对它们进行正确排序。

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.

云淡月浅 2025-01-03 11:05:11

您可以使用自定义比较器

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

,并且可以像这样使用比较器

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

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());
傾旎 2025-01-03 11:05:11

如果您使用 .NET 2.0 并且无法使用 Linq,您可以尝试:

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

这假设分隔符始终是逗号,如果需要,请添加您自己的验证代码。

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.

柠檬 2025-01-03 11:05:11

这是我不久前写的一些代码,我确信有一种更有效的方法可以做到这一点,但这确实有效。
要使用它,包括:

using System.Linq;

然后调用 use a linq query:

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

当然包括相关方法:

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

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);
    }
囚我心虐我身 2025-01-03 11:05:11

对字符串的数字部分进行排序:

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

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);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文