按自定义顺序排序String数组

时间:2012-05-28 08:58:16

标签: c# sorting arrays

我想按照相同的顺序对字符串数组中的“文本文件”,“图像文件”,“音频文件”,“视频文件”,“应用程序文件”,“其他文件”等固定字符串进行排序我已经提到了。

例子1,如果我的字符串数组输入是这样的

inputval[0] = "Other files";
inputval[1] = "Image files";
inputval[2] = "Text files";

我的输出数组应该有这样的值

outputval[0] = "Text files";
outputval[1] = "Image files";
outputval[2] = "Other files";

示例2,如果我的字符串数组输入是这样的

inputval[0] = "Application files";
inputval[1] = "Image files";
inputval[2] = "Video files";

我的输出数组应该有这样的值

outputval[0] = "Image files";
outputval[1] = "Video files";
outputval[2] = "Application files";

请有人帮助我实现这个目标

4 个答案:

答案 0 :(得分:7)

使用提供给IComparer<string>的{​​{1}}的粗略实现有效。有各种潜在的缺点,但我会留给你们(就像字符串需要完全匹配,否则它们不会正确排序)。

它只是使用代表正确顺序的字符串的内部列表,然后将它们在该列表中的序数相互比较。

Array.Sort

答案 1 :(得分:1)

实施ICompare,然后您可以OrderBy使用ICompare来获取自定义排序。查看MSDN ICompare article

即。像,

public class MyCompare : ICompare<string>
{
    // Because the class implements IComparer, it must define a 
    // Compare method. The method returns a signed integer that indicates 
    // whether s1 > s2 (return is greater than 0), s1 < s2 (return is negative),
    // or s1 equals s2 (return value is 0). This Compare method compares strings. 
    public int Comapre(string s1, string s2)
    {
        // custom logic here
    }
}

答案 2 :(得分:1)

因为你想要的不是很清楚。所以我考虑到inputval中没有重复。

string[] fixed_array =  { "Text files", "Image files", "Audio files", 
                        "Video files", "Application Files", "Other files" };

让我们说

inputval[0] = "Other files";
inputval[1] = "Image files";
inputval[2] = "Text files";

这样做

string[] outputval =
          fixed_array.Select(x => inputval.Contains(x) ? x : "-1")
                     .Where(x => x != "-1").ToArray();

所以outputval将是

outputval[0] = "Text files";
outputval[1] = "Image files";
outputval[2] = "Other files";

答案 3 :(得分:0)

只需在开头添加数字的字符串,然后将其添加到排序列表中。

如“0,文本文件”,“1,图像文件”,“2,音频文件”,“3,视频文件”,“4,应用程序文件”,“4,其他文件”

然后在使用时删除“,”之前的字符串..