Neil Hodges
Neil Hodges

Reputation: 127

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:

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?

Upvotes: 0

Views: 68

Answers (1)

Jamiec
Jamiec

Reputation: 136124

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.

Upvotes: 1

Related Questions