2011-03-23 18 views
2

問題更新通過LINQ格式化使用從泛型列表值的字符串

我有一個可以包含以下值泛型列表:

Sector 1 
Sector 2 
Sector 4 

或以下值:

All Sectors 

我想這樣的字符串格式如下:

Sector 1 & 2 & 4 - 

All Sectors - 

目前,我有以下的代碼格式化一樣。它有效,但非常複雜。

string retrieveSectors += sectors.Count == 0 
           ? string.Empty 
           : sectors.OrderBy(
           y => 
           y.Sector.Substring(
           y.Sector.Length - 1, 1)). 
           GroupBy(g => g.Sector).Select(
           g => g.First()).ToList().Aggregate(
           retrieveSectors, 
           (current, y) => 
           (current == retrieveSectors 
           ? current + 
           y.Sector 
           : current + " & " + 
           y.Sector. 
           Substring(
           y.Sector. 
           Length - 1, 1))) + " - " 

在上面的代碼中,變量扇區是通用列表。有人能幫助我以簡單的方式獲得結果嗎?或者可以修改上面的代碼,使其更易於理解。

任何幫助表示讚賞。由於

+0

有多少個扇區存在? – renatoargh 2011-03-23 19:06:36

+0

它在上面更新的問題中提到。該列表可能包含「所有部門」或「部門1,部門2,部門4」,或者可能爲空。我需要針對所有三種場景的解決方案。請檢查更新的問題 – reggie 2011-03-23 19:08:55

+0

認爲我已經得到了明確的答案,請看下面! – renatoargh 2011-03-23 19:16:37

回答

1

也許有一點更簡單:

string retrieveSectors = 
     string.Format(
     "sectors {0} -", 
     sectors.Select(s => s.Replace("sector ", "").Replace("|", "")) 
      .OrderBy(s => s) 
      .Aggregate((a, b) => string.Format("{0} & {1}", a, b)) 
     ); 
+0

如果「所有扇區」進來,該解決方案不起作用。請檢查問題,我已再次更新。對不起前一個。 – reggie 2011-03-23 19:03:47

+0

另外,如果通用列表爲空,則會給出錯誤。 – reggie 2011-03-23 19:07:17

1

嘗試了這一點!

List<String> list = new List<String>() { "Sector 1", "Sector 2", "Sector 4" }; 

(list.Count == 0 ? "Not any sector " :  
((list.Contains("All Sectors") ? "All Sectors " : 
    "Sector " + String.Join(" & ", list.OrderBy(c => c).ToArray()) 
     .Replace("Sector", String.Empty)))) + " - " 

而且連續工作:

List<String> list = new List<String>(); 
List<String> list = new List<String>() { "All Sectors" }; 
0

假設source就是扇區存儲任何類型的IEnumerable<string>,可能是更簡潔的語法是:

String.Join(" & ", source).Replace(" Sector ", " ") 

或者這一點,如果source威力無序,你想要訂購扇區號碼:

String.Join(" & ", source.OrderBy(s => s)).Replace(" Sector ", " ") 

最後,最終細化檢查「沒有任何部門都」像雷納託的回答是:

source.Any() ? String.Join(" & ", source.OrderBy(s => s)).Replace(" Sector ", " ") : "No sectors" 

所有這些解決方案在你的第一個(簡單地提到2例反正工作,2後是增強版本,用於處理可能合理發生並感興趣的附加情況)。

+0

看起來不算太糟糕,我喜歡在kevev22答案中使用Aggregate。我想知道哪些解決方案更具性能。 – JTew 2011-05-23 02:22:36

相關問題