LINQ使用通用列表中的值格式化字符串 [英] Formatting a string using values from a generic list by LINQ
本文介绍了LINQ使用通用列表中的值格式化字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问题已更新
我有一个通用列表,其中可以包含以下值:
I have a generic list which can contains the following values:
Sector 1
Sector 2
Sector 4
或以下值:
All Sectors
我想用以下字符串格式化此值:
I want to format this values in a string like this:
Sector 1 & 2 & 4 -
或
All Sectors -
目前,我有以下代码来对其进行格式化.它可以工作,但是非常复杂.
Currently, I have the following code to format the same. It works, but is very complicated.
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))) + " - "
在上面的代码中,可变扇区是通用列表.有人可以帮助我以简化的方式获得结果吗?或者可以修改上面的代码,使其更易于理解.
In the above code, the variable sector is the generic list. Can someone help me to attain the results in a simplified way.? Or may be modify the above code so that it is more understandable.
任何帮助表示赞赏.谢谢
Any help appreciated. Thanks
推荐答案
也许更简单一些:
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))
);
这篇关于LINQ使用通用列表中的值格式化字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文