【问题标题】:How to sort a List of strings by multiple conditions如何按多个条件对字符串列表进行排序
【发布时间】:2020-06-02 07:58:17
【问题描述】:

我有一个看起来像这样的字符串列表(完全未排序):

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

它应该被排序为如下所示:

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

或者这个(排序方式可以选择)

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

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

我对整个排序的方法有点肮脏,一点也不圆滑,而且只解决了第二种排序方式。

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

希望你们能告诉我如何更好更短地做到这一点^^

【问题讨论】:

  • 您可以为此编写自己的比较器。能分享一下具体的排序规则吗? errorTps 是什么?

标签: c# list if-statement foreach


【解决方案1】:

您发布的代码可以使用 LINQ 完成:

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

首先会根据字符串是否包含“\t complete”进行排序,然后会根据字符串本身进行排序。最后,将排序后的结果复制到一个新的列表中。

【讨论】:

  • 他的代码示例不完整,但在他的问题中,他解释说排序应该是可配置的。先上标题后完成,或先完成后上标题。您的解决方案并非如此。
猜你喜欢
  • 1970-01-01
  • 2021-06-10
  • 1970-01-01
  • 1970-01-01
  • 2015-08-08
  • 2021-12-14
  • 2014-04-15
  • 2020-06-13
  • 1970-01-01
相关资源
最近更新 更多