函数式编程-C#-IEnumerable到分隔字符串
本文关键字:分隔 字符串 -C#-IEnumerable 编程 函数 | 更新日期: 2023-09-27 17:47:24
将
IEnumerable<string>
转换为分隔字符串的函数式编程方法是什么?我知道我可以使用循环,但我正在努力理解函数式编程。
这是我的例子:
var selectedValues =
from ListItem item in checkboxList.Items
where item.Selected
select item.Value;
var delimitedString = ??
或者我可以只在第一个var赋值中做到这一点(将每个结果附加到前一个(?
string.Join(", ", string[] enumerable)
这里有一个StringBuilder
的例子。好的方面是Append()
返回StringBuilder
实例本身。
return list.Aggregate( new StringBuilder(),
( sb, s ) =>
( sb.Length == 0 ? sb : sb.Append( ',' ) ).Append( s ) );
var delimitedString = selectedValues.Aggregate((x,y) => x + ", " + y);
var delimitedString = string.Join(",", checkboxList.Items.Where(i => i.Selected).Select(i => i.Value).ToArray());
AviewAnew是最好的答案,但如果你想要的是学习如何在函数中思考,那么你应该使用折叠操作(或在NET中称为聚合(。
items.Aggregate((accum, elem) => accum + ", " + elem);
在这种情况下,函数方法可能不是最适合的,因为没有LINQ"ForEach",并且您不想使用字符串串联:您想使用StringBuilder。你可以使用ToArray(上面刚刚出现的一个例子(,但我很想简单地使用:
StringBuilder sb = new StringBuilder();
foreach(ListViewItem item in checkboxList.SelectedItems) {
if(sb.Length > 0) sb.Append(',');
sb.Append(item.Text);
}
string s = sb.ToString();
不是函数式编程,但它有效。。。当然,如果您的源已经一个字符串[],那么字符串。加入是完美的。(LINQ是一个很好的工具,但不一定总是适用于每项工作的最佳工具(
这里有一种LINQ/函数式的方法。
string[] toDelimit = CallSomeFunction();
return toDelimit.Aggregate((x, y) => x + "," + y);
这是3.5兼容:
var selectedValues = String.Join(",", (from ListItem item in checkboxList.Items where item.Selected select item.Value).ToArray());