c#按对象列表排序

时间:2018-10-23 20:58:34

标签: c# asp.net

我有一个具有多个字段的对象列表/集合。其中之一是文件名。

我正在根据文件名进行排序,但没有得到正确的结果。

列表:

"552939_VVIDEO9.mp4"
"552939_VVIDEO8.mp4"
"552939_VVIDEO13.mp4"
"552939_VVIDEO12.mp4"
"552939_VVIDEO7.mp4"
"552939_VVIDEO6.mp4"
"552939_VVIDEO2.mp4"
"552939_VVIDEO16.mp4"
"552939_VVIDEO10.mp4"
"552939_VVIDEO3.mp4"
"552939_VVIDEO11.mp4"
"552939_VVIDEO4.mp4"
"552939_VVIDEO1.mp4"
"552939_VVIDEO15.mp4"
"552939_VVIDEO14.mp4"
"552939_VVIDEO17.mp4"


  List<WfVideo> orderVideo = ProductData.Videos.OrderBy(o => o.Filename, StringComparer.InvariantCultureIgnoreCase).ToList();

我得到的结果:

VOD1
VOD2
VVIDEO1
VVIDEO10
VVIDEO11
VVIDEO12
VVIDEO13
VVIDEO14
VVIDEO15
VVIDEO16
VVIDEO17
VVIDEO2
VVIDEO3
VVIDEO4
VVIDEO5
VVIDEO6

排序不正确吗?

1 个答案:

答案 0 :(得分:1)

如果您只想对这些文件进行数字排序,则可以传递一个比较器以进行排序,以实现所需的规则。这将根据文件名的编号对其进行排序:

List<string> files = new List<string>
    {
        "552939_VVIDEO9.mp4",
        "552939_VVIDEO8.mp4",
        "552939_VVIDEO13.mp4",
        "552939_VVIDEO12.mp4",
        "VOD1.mp4",
        "552939_VVIDEO6.mp4",
        "VOD2.mp4",
        "552939_VVIDEO2.mp4",
        "552939_VVIDEO16.mp4",
        "552939_VVIDEO10.mp4",
        "552939_VVIDEO3.mp4",
        "552939_VVIDEO11.mp4",
        "552939_VVIDEO4.mp4",
        "552939_VVIDEO1.mp4",
        "552939_VVIDEO15.mp4",
        "552939_VVIDEO14.mp4",
        "552939_VVIDEO17.mp4"
    };
        files.Sort((a, b) => {
            int an = 0;
            int bn = 1;
            var regex = new Regex("([0-9]+).mp4", RegexOptions.IgnoreCase);
            var aGroups = regex.Match(a).Groups;
            var bGroups = regex.Match(b).Groups;
            var aidx = aGroups.Count > 1 ? 1 : 0;
            var bidx = bGroups.Count > 1 ? 1 : 0;
            an = int.Parse(aGroups[aidx].Value);
            bn = int.Parse(bGroups[bidx].Value); 
            if (an == bn)
                return 0;
            if (an < bn)
                return -1;
            return 1;
        });
        foreach (var file in files)
        {
            Console.WriteLine(file);
        }
        Console.ReadKey();

输出:

VOD1.mp4
552939_VVIDEO1.mp4
VOD2.mp4
552939_VVIDEO2.mp4
552939_VVIDEO3.mp4
552939_VVIDEO4.mp4
552939_VVIDEO6.mp4
552939_VVIDEO8.mp4
552939_VVIDEO9.mp4
552939_VVIDEO10.mp4
552939_VVIDEO11.mp4
552939_VVIDEO12.mp4
552939_VVIDEO13.mp4
552939_VVIDEO14.mp4
552939_VVIDEO15.mp4
552939_VVIDEO16.mp4
552939_VVIDEO17.mp4

请注意,可能需要进行其他一些错误检查。您可以偏离路线扩展此“比较器”功能,使其适用于您希望的任何规则。