[英]How to sort a List of strings by multiple conditions
我有一個看起來像這樣的字符串列表(完全未排序):
[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);
}
希望你們能告訴我如何做得更好更短^^
您發布的代碼可以使用 LINQ 完成:
var sortedTps = tpByProduct.OrderBy(x => x.Contains("\t complete")).ThenBy(x => x).ToList();
首先它會在字符串是否包含“\\t complete”之后排序,然后它會在字符串本身之后排序。 最后,排序結果被復制到一個新列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.