user222427
user222427

Reputation:

C# List<string> OrderBy Split

I'm trying to just Order a list by the value after a split.

For example my data looks like this.

Z|2  
A|1

I want my list to be order by the value after the split

so I would get

A|1  
Z|2  

This is what i'm using but I get the error:

{"Input string was not in a correct format."}

All = All.OrderBy(s => int.Parse(s.Split('|')[1])).ToList();

Any help would be awesome! Thanks!

Upvotes: 3

Views: 4071

Answers (4)

cuongle
cuongle

Reputation: 75306

You need to skip invalid format first, assume put in the top:

All = All.OrderBy(s => {
    var parts = s.Split('|');

    if (parts.Length != 2)
        return int.MinValue;

    int value;
    if (int.TryParse(parts[1], out value))
        return value;

    return int.MinValue;
});

Upvotes: 1

Guffa
Guffa

Reputation: 700342

You can use TryParse if you have values that you are not sure about. This would put any values that are not possible to parse last in the list:

All = All.OrderBy(s => {
  int value;
  if (!Int32.TryParse(s.Split('|')[1], out value)) {
    value = Int32.MaxValue;
  }
  return value;
}).ToList();

(Note: The largest possible int value is used to place those items last in the list, if you would have any other items with the value 2147483648, they would be mixed with those. For a solution that works with that values too, you would need to create a comparer instead of a delegate that merely extracts the value from the string.)

Upvotes: 1

Joe Enos
Joe Enos

Reputation: 40393

Your code is just fine - you must have some invalid data. Double-check the values in your initial list to make sure you don't have any non-numeric values after the pipe, or anything else like that.

EDIT

You could always catch errors and handle them differently, like:

// This would put all failures at the top of the list
All = All.OrderBy(s => {
    try { return int.Parse(s.Split('|')[1]); }
    catch { return 0; }
}).ToList();

Upvotes: 0

Jon
Jon

Reputation: 437376

This would work:

All = All.OrderBy(s => int.Parse(s.Split('|').Last())).ToList();

What would work even better though would be to have a list of a structured type instead of a list of dumb strings. For example, you could have a list of Tuple<string, int> and simply sort it by the second member. You could also put the tuple into an ordered container and have sorting done automatically.

Upvotes: 6

Related Questions