c# - 通过 LINQ 使用通用列表中的值格式化字符串

标签 c# linq string string-formatting

问题已更新

我有一个通用列表,其中可以包含以下值:

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))) + " - "

在上面的代码中,变量sector就是泛型列表。有人可以帮助我以简化的方式获得结果吗?或者可以修改上面的代码,使其更易于理解。

感谢任何帮助。谢谢

最佳答案

也许更简单一点:

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

关于c# - 通过 LINQ 使用通用列表中的值格式化字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5409890/

相关文章:

c# - WPF - 未找到 src 类型

c# - 如何让应用程序停止并运行调试器?

c# - 从 catch block 中跳出 for 循环

C# LINQ - 将嵌套字典转换为列表

c# - 使用 linq 选择子列表包含的列表是另一个列表中的所有项目

Ruby 字符串拆分为多个字符

php - 在提交 MySQL 之前将字符串转换为日期

c# - Mono.Cecil 能否修改已加载到 AppDomain 中的代码?

c# - Linq select group by where语法

python - 如何检测Python中未解码的字符?