简体   繁体   中英

Not able to sort list in a certain way using OrderBy C# functionality

EDIT - the correct result on the right (in the examples below) is how excel is doing the sort and what I am trying to accomplish with the OrderBy in C#.

I have the following OrderBy statement:

tempList.OrderBy(x => x.value);

and get the following results:

01P
41
90

but I need it to be the following instead:

41
90
01P

Is there a way using OrderBy to accomplish this type of sort? I have already tried adding all the variations of StringComparison.(type) but I could not ever get the sorting to work.

Any help is much appreciated!

More Examples below:

Sorted by OrderBy:                        What is needed instead:

Example 1)

35                                        7
7                                         35

Example 2)

44K                                       692
692                                       44K

Example 3)

0EP                                       629
0ET                                       0EP
692                                       0ET

Example 4)

10W                                       110
110                                       10W

I think you want a numeric sort before. Try like below:

string[] myArray = { "0EP", "0ET", "692" };

var result = myArray.OrderBy(a => !int.TryParse(a, out var _)).ThenBy(a => a).ToList();

While I liked kkoyuncu's answer, it relies on two OrderBy's. You could eliminate that by having a Custom Comparer.

public class CustomComparer : IComparer<string>
{
   public int Compare(string stringA, string stringB)
    {
        var isValueAInt = int.TryParse(stringA, out var valueA);
        var isValueBInt = int.TryParse(stringB, out var valueB);

        if(isValueAInt && isValueBInt)
        {
            return valueA - valueB;
        }
        else if(isValueAInt && !isValueBInt)
        {
            return-1;
        }
        else if(!isValueAInt && isValueBInt)
        {
            return 1;
        }
        return String.Compare(stringA,stringB);

    }
}

Now your code would look like,

string[] myArray = { "35", "7","110","10W","0EP","0ET","692"};
var comparer = new CustomComparer();
var result = myArray.OrderBy(a=>a,comparer);

Output

7 
35 
110 
692 
0EP 
0ET 
10W 

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