2011-03-23 49 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