2017-04-26 19 views
0

我有一個字符串的集合是如下:在LINQ爲了忽略串by子句C#

"[Unfinished] Project task 1" 
"Some other Piece of work to do" 
"[Continued] [Unfinished] Project task 1" 
"Project Task 2" 
"Random other work to do" 
"Project 4" 
"[Continued] [Continued] Project task 1" 
"[SPIKE] Investigate the foo" 

我想要做的就是爲了這些字符串按字母順序基於字符串,而忽略了廣場上的值括號。所以我想最終的結果是:

"[SPIKE] Investigate the foo" 
"Project 4" 
"[Continued] [Continued] Project task 1" 
"[Continued] [Unfinished] Project task 1" 
"[Unfinished] Project task 1" 
"Project Task 2" 
"Random other work to do" 
"Some other Piece of work to do" 

問:

怎麼能這樣在LINQ來實現,這是我必須:

collection.OrderBy(str => str) 

回答

3

給出一個簡單的正則表達式:

var rx = new Regex(@"\[[^]]*\] *"); 

,搜索括號內的文字(後跟可選空格),您可以:

var ordered = collection.OrderBy(str => rx.Replace(str, string.Empty)); 

這會刪除括號內的文字,以文字排序。

注意,沒有「二次排序」在這裏,所以:

"[Continued] [Unfinished] Project task 1" 
"[Continued] [Continued] Project task 1" 

將保持在相同的順序寫入(未完,待續)並不會逆轉。

如果你想訂購的二次,然後:

var ordered = collection 
    .OrderBy(str => rx.Replace(str, string.Empty)) 
    .ThenBy(str => str); 

使用整個字符串作爲二次訂貨會是好的。但隨後:

"[Continued] [Unfinished] project task 1" 
"[Continued] project task 1" 

仍將作爲寫入(小寫字母是[]以Unicode),同時

"[Continued] [Unfinished] Project task 1" 
"[Continued] Project task 1" 

將變得

"[Continued] Project task 1" 
"[Continued] [Unfinished] Project task 1" 

因爲上殼體字母在Unicode之前是[]

+0

奇妙的是,這正是我所需要的。一旦足夠的時間過去,我會接受這個答案。 –

6

這聽起來像你應該編寫一個方法來檢索「不在括號內的字符串部分」(例如使用正則表達式)。然後你可以使用:

var ordered = collection.OrderBy(RemoveTextInBrackets); 

RemoveTextInBrackets方法可能只想在字符串的開始刪除的東西,也是繼它的空間。

完整的示例:

using System; 
using System.Linq; 
using System.Text.RegularExpressions; 

public class Program 
{ 
    private static readonly Regex TextInBrackets = new Regex(@"^(\[[^\]]*\])*"); 

    public static void Main() 
    { 
     var input = new[] 
     { 
      "[Unfinished] Project task 1 bit", 
      "Some other Piece of work to do", 
      "[Continued] [Unfinished] Project task 1", 
      "Project Task 2", 
      "Random other work to do", 
      "Project 4", 
      "[Continued] [Continued] Project task 1", 
      "[SPIKE] Investigate the foo", 
     }; 

     var ordered = input.OrderBy(RemoveTextInBrackets); 

     foreach (var item in ordered) 
     { 
      Console.WriteLine(item); 
     } 
    } 

    static string RemoveTextInBrackets(string input) => 
     TextInBrackets.Replace(input, ""); 
} 
0

嘗試擴展方法的一些組合如下所示:

inputList.OrderBy(x=> x.Contains("]")? x.Substring(x.LastIndexOf("]")):x) 

Working Example

0

與上述類似的建議,這裏是我的實現。

var newCollection = collection.OrderBy((s) => 
    { 
     if (s.Contains("]")) 
     { 
      string pattern = "\\[(.*?)\\] "; 
      Regex rgx = new Regex(pattern); 
      return rgx.Replace(s, ""); 
     } 
     else 
     { 
      return s; 
     } 
    }).ToList(); 
    }