gpt4 book ai didi

c# - 为什么 .ForEach() 在 IList 而不是 IEnumerable 上?

转载 作者:IT王子 更新时间:2023-10-29 03:48:57 26 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why is there not a ForEach extension method on the IEnumerable interface?

我在编写 LINQ-y 代码时注意到 .ForEach()是一个很好用的成语。例如,下面是一段接受以下输入并产生这些输出的代码:

{ "One" } => "One"
{ "One", "Two" } => "One, Two"
{ "One", "Two", "Three", "Four" } => "One, Two, Three and Four";

还有代码:

private string InsertCommasAttempt(IEnumerable<string> words)
{
List<string> wordList = words.ToList();
StringBuilder sb = new StringBuilder();
var wordsAndSeparators = wordList.Select((string word, int pos) =>
{
if (pos == 0) return new { Word = word, Leading = string.Empty };
if (pos == wordList.Count - 1) return new { Word = word, Leading = " and " };
return new { Word = word, Leading = ", " };
});

wordsAndSeparators.ToList().ForEach(v => sb.Append(v.Leading).Append(v.Word));
return sb.ToString();
}

请注意插入的 .ToList().ForEach() 之前在倒数第二行。

为什么是.ForEach()IEnumerable<T> 上不能作为扩展方法使用?像这样的例子,看起来很奇怪。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com