简体   繁体   中英

C# Order/Sorting List by String Name - [n]x[n]

I have a List in C# that needs sorting by Name. The Names are sizes of Sheds so start like this:

  • 4x4 Apex Shed
  • 20x6 Apex Shed
  • 10x6 Apex Shed

When I order them by name it picks up 10x6 as the first, but the 4x4 should be first. I think the 1 is being picked up and it's being ordered that way.

I have this:

allProducts = allProducts.OrderBy(x => x.Name).ToList();

What would be the best way to order them by name - [n]x[n] and most efficient?

It's not particularly "efficient" because string mashing this sort of thing just isnt, but you could use Regex to pull out the dimensions and order that based on your rules. Say your rule is "order by area" that would just be the width multiplied by the depth:

var regex = new Regex(@"(?<a>\d+)\s*x\s*(?<b>\d+)");
var input = new List<string>
{
    "4x4 Apex Shed",
    "20x6 Apex Shed",
    "10x6 Apex Shed"
};
    
var result = input.OrderBy(x => {
        var match = regex.Match(x);
        var a = int.Parse(match.Groups["a"].Value);
        var b = int.Parse(match.Groups["b"].Value);
        return a * b;
});

Live example: https://dotnetfiddle.net/SDDJgy

If you want to make this efficient store the data as an object with width, depth and name properties and order appropriately instead of trying to parse these values out of a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM