15,907,687 members
See more:
C#
```I am working on one project and now i am stuck on very silly program i.e sorting list.
I have list of items range between 0-500 . and items like (e.g "45848^kjf,10" , "450240^jdk,20" , "448278^dj,30").
My current code sort list in decending order but the order gets wrong result . i.e

1. 45848^kjf,10
2. 450240^jdk,20
3. 448278^dj,30

I want to sort list items with respective to the number before "^" this symbol and 45848 is smaller than below two numbers so, my expected result is

1. 450240^jdk,20
2. 448278^dj,30
3. 45848^kjf,10

How can i get this result?  here is my code,```

What I have tried:

C#
```listcode.Sort(); // listcode is String list
listcode.Reverse();
```
Posted
Updated 15-Nov-16 18:18pm

## Solution 1

try

C#
```string[] items = { "45848^kjf,10", "450240^jdk,20", "448278^dj,30" };
var listcode = items.ToList();
var result =  listcode.Select(k => new { value = int.Parse( k.Substring(0, k.IndexOf('^'))), item = k }).OrderByDescending(k => k.value).Select(k => k.item).ToList();```

Member 11543226 16-Nov-16 0:36am
Thanks this works

## Solution 2

There are two ways of doing this - you either need to implement an `IComparer<string>`, or a Comparison delegate. The second method can easily be done as a lambda delegate in your call to the sort method.

C#
```listcode.Sort(delegate(string1, string2) {
int num1, num2;
try {
num1 = int.Parse(string1.SubString(0, string1.IndexOf('^')));
num2 = int.Parse(string2.SubString(0, string2.IndexOf('^')));
return num1.CompareTo(num2);
}
catch {
// Handle the case one of the strings are not in correct format
}
});```

Otherwise, create a class that implements IComparer<string>. This class will have a `Compare(string1, string2)` method in it, which will pretty much be identical to the lambda delegate above. Then you call `listcode.Sort(new MyComparerClass());`. Look at the MSDN documentation for IComparer[^] for an example of how to implement.

v2