如何排序字符串列表? [英] How to sort string list?

查看:107
本文介绍了如何排序字符串列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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:

listcode.Sort(); // listcode is String list
               listcode.Reverse();

推荐答案

尝试



try

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();


有两种方法可以做这个 - 您需要实现 IComparer< string> 或比较委托。在调用sort方法时,第二种方法可以很容易地作为lambda委托来完成。



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.

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
    }
});





否则,创建一个实现IComparer的类< string> ;。这个类将有一个比较(string1,string2)方法,它几乎与上面的lambda委托相同。然后你调用 listcode.Sort(new MyComparerClass()); 。查看 IComparer的MSDN文档 [ ^ ]以获取如何实现的示例。



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.


这篇关于如何排序字符串列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆