如何对列表条目进行排序? [英] How do I sort list entries?

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

问题描述

我的列表中有以下数据,我想按照以下顺序对其进行排序。



条目如下,



 List< String> codeb = new List< string>(); 
codeb.Add(CH-01-0223,B);
codeb.Add(CH-01-0220,A);
codeb.Add(AL-01-0023,B);
codeb.Add(AL-01-0200,A);
codeb.Add(AL-02-0101,B);
codeb.Add(AL-02-0201,A);





我想得到如下结果,



 AL-01-0200,A 
AL-01-0023,B
AL-02-0201,A
AL-02-0101,B
CH -01-0220,A
CH-01-0223,B





我尝试了什么:



我尝试过使用

 codeb.sort()





但它给出如下排序,

 AL-01-0023,B 
AL-01 -0200,A
AL-02-0101,B
AL-02-0201,A
CH-01-0220,A
CH-01-0223,B

解决方案

您不能只使用标准字符串排序并期望它能为您提供非标准字符串顺序的结果 - 和字符串排序是基于从左到右依次比较每个字符,整个比较基于第一个不同的字符。



你需要提供一个自定义排序方法并从OrderBy调用它:

 var sorted = codeb.OrderBy(s => s,Co mparer< string> .Create((l,r)=> MySortMethod(l,r))); 



您的方法如下所示:

 private int MySortMethod(string l,string r)
{
...
}

如果l小于r则返回-1,如果它们相同则返回0 ,如果l大于r,则为1。



因为我不知道为什么你需要的排序顺序就是这样,你必须自己写这个位!


I have following data in my list and I want to sort it in following order.

entries are like below,

List<String> codeb = new List<string>();
           codeb.Add("CH-01-0223,B");
           codeb.Add("CH-01-0220,A");
           codeb.Add("AL-01-0023,B");
           codeb.Add("AL-01-0200,A");
           codeb.Add("AL-02-0101,B");
           codeb.Add("AL-02-0201,A");



I want result like below,

AL-01-0200,A
AL-01-0023,B
AL-02-0201,A
AL-02-0101,B
CH-01-0220,A
CH-01-0223,B



What I have tried:

I tried using

codeb.sort()



but it gives sorting like below,

AL-01-0023,B
AL-01-0200,A
AL-02-0101,B
AL-02-0201,A
CH-01-0220,A
CH-01-0223,B

解决方案

You can't just used a "standard string sort" and expect it to give you results that aren't in standard string order - and string ordering is based on comparing each character in turn from the left to the right and the whole comparison being based on the first different character.

You need to provide a custom sort method and call it from OrderBy:

var sorted = codeb.OrderBy(s => s, Comparer<string>.Create((l, r) => MySortMethod(l, r)));


Your method will look like this:

private int MySortMethod(string l, string r)
    {
    ...
    }

And returns -1 if l is less than r, 0 if they are the same, and 1 if l is greater than r.

Since I have no idea why your required sort order is the way it is you will have to write that bit yourself!


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

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