Taranjit Kang
Taranjit Kang

Reputation: 2580

c# Order By on List of Objects

I have a list/collection of objects with multiple fields. One of them being filename.

I am sorting based on filename but not getting the correct results.

List:

"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();

Result I am getting:

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

Is the sorting incorrect?

Upvotes: 0

Views: 101

Answers (1)

Espen
Espen

Reputation: 2576

If you want to sort these files after the number only, you could pass a Comparer to Sort that implements the rules you want. This sorts the filenames according to their number:

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

Output:

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

Note some additional error checking may be needed. You can offcourse extend this Comparer function to work for whatever rules you wish.

Upvotes: 1

Related Questions