简体   繁体   English

如何按多个条件对字符串列表进行排序

[英]How to sort a List of strings by multiple conditions

I have a List of strings that looks like this (completely unsorted):我有一个看起来像这样的字符串列表(完全未排序):

[Title b] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title a] \t [text] \t complete
[Title c] \t [text] \t complete
...

It shall be sorted to look like either this:它应排序为如下所示:

[Title a] \t [text] \t complete
[Title a] \t [text] \t incomplete
[Title b] \t [text] \t complete
[Title c] \t [text] \t complete
...

Or this (which way it shall be sorted is selectable)或者这个(它应该排序的方式是可选的)

[Title a] \t [text] \t complete
[Title j] \t [text] \t complete
[Title s] \t [text] \t complete
...

[Title b] \t [text] \t incomplete
...

My approach on this whole sorting thing is kinda dirty and not sleek at all and also only solves the second way of sorting.我对整个排序的方法有点脏,一点也不光滑,也只解决了第二种排序方式。

List<string> sortedTps = new List<string>();
List<string> completeTps = new List<string>();
List<string> incompleteTps = new List<string>();
List<string> errorTps = new List<string>();

foreach (string tp in tpByProduct)
{
    if (tp.Contains("\t complete"))
    {
        completeTps.Add(tp);
    }
    else if (tp.Contains("\t incomplete"))
    {
        incompleteTps.Add(tp);
    }
 }

 completeTps.Sort();
 incompleteTps.Sort();

 foreach(string tp in completeTps)
 {
    sortedTps.Add(tp);
 }

 foreach(string tp in incompleteTps)
 {
    sortedTps.Add(tp);
 }

Hope you guys can show me how to do this better and shorter ^^希望你们能告诉我如何做得更好更短^^

The Code you posted can be done with LINQ:您发布的代码可以使用 LINQ 完成:

var sortedTps = tpByProduct.OrderBy(x => x.Contains("\t complete")).ThenBy(x => x).ToList();

First it will sort after whether the string contains "\\t complete", then it will sort after the string itself.首先它会在字符串是否包含“\\t complete”之后排序,然后它会在字符串本身之后排序。 In the end, the sorted result ist copied into a new list.最后,排序结果被复制到一个新列表中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM