C#按字母顺序和长度对Arraylist字符串进行排序 [英] C# sort Arraylist strings alphabetical and on length

查看:26
本文介绍了C#按字母顺序和长度对Arraylist字符串进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对 StringArrayList 进行排序.

I'm trying to sort an ArrayList of String.

给定:

{A,C,AA,B,CC,BB}

Arraylist.Sort 给出:

{A,AA,B,BB,C,CC}

我需要的是:

{A,B,C,AA,BB,CC}

推荐答案

这有点老派,但我选择了 IComparer Interface ...

This is kind of old school but, I went the IComparer Interface . . .

public class SortAlphabetLength : System.Collections.IComparer
{
    public int Compare(Object x, Object y)
    {
        if (x.ToString().Length == y.ToString().Length)
            return string.Compare(x.ToString(), y.ToString());
        else if (x.ToString().Length > y.ToString().Length)
            return 1;
        else
            return -1;
    }
}

然后测试一下...

class Program
{
    static void Main(string[] args)
    {
        ArrayList values = new ArrayList()
        {
            "A","AA","B","BB","C","CC"
        };

        SortAlphabetLength alphaLen = new SortAlphabetLength();
        values.Sort(alphaLen);

        foreach (string itm in values)
            Console.WriteLine(itm);
    }
}

输出:

A
B
C
AA
BB
CC

这篇关于C#按字母顺序和长度对Arraylist字符串进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆