C# 尝试将对象附加到foreach循环中的可枚举项

C# 尝试将对象附加到foreach循环中的可枚举项,c#,foreach,append,iteration,C#,Foreach,Append,Iteration,我正在做一个C#练习来创建一个操作,该操作接受一个集合,对集合中的每个对象执行一个函数,并返回一个修改过的对象集合 我的代码目前如下: public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func) { IEnumerable<U> output = Enumerable.Empty<U>()

我正在做一个C#练习来创建一个操作,该操作接受一个集合,对集合中的每个对象执行一个函数,并返回一个修改过的对象集合

我的代码目前如下:

public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
{
    IEnumerable<U> output = Enumerable.Empty<U>();

    foreach (T item in collection)
    {
        output.Append(func(item));
    }

    return output;
}
public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
{
    foreach (T item in collection)
    {
        yield return func(item);
    }
}
但这并没有解决任何问题


我做了一些研究,但找不到任何与我想做的完全相同的例子。我读了一些关于闭包的东西,但不能真正理解它,因为我是C#的新手。

回答你的实际问题:闭包不起作用的原因是

output.Append(func(item));
不更改
输出
——而是返回一个新序列,该序列是
func(item)
附加到
输出
。因此,当您最终返回
output
时,您只是返回原始的空序列

您可以通过以下简单的更改来完成您的工作:

output = output.Append(func(item));
但是,这并不是一种有效的方法-您最好使用以下方法修改您的方法:

public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
{
    IEnumerable<U> output = Enumerable.Empty<U>();

    foreach (T item in collection)
    {
        output.Append(func(item));
    }

    return output;
}
public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
{
    foreach (T item in collection)
    {
        yield return func(item);
    }
}
公共静态IEnumerable累积(此IEnumerable集合,Func Func)
{
foreach(集合中的T项)
{
收益回报函数(项目);
}
}
但请注意,这更简单地表示为:

public static IEnumerable<U> Accumulate<T, U>(this IEnumerable<T> collection, Func<T, U> func)
{
    return collection.Select(item => func(item));
}
公共静态IEnumerable累积(此IEnumerable集合,Func Func)
{
返回集合。选择(项=>func(项));
}

但是了解如何使用
yield
来实现这一点很有用,这样您就可以为更复杂的类似Linq的问题编写解决方案。

通常,当我想要实现这种行为时,我会使用C迭代器。 当您希望对某种数据进行迭代,并在每次迭代时返回附加到结果集合的值时,它们非常有用


看看文档:

正如您所知,这也可以在Linq中实现:
var output=collection.Select(x=>SomeFunction(x))附加不会修改您的集合,它会返回一个新集合。顺便说一下,这适用于所有LINQ方法。或者更缩写为:
var output=collection.Select(SomeFunction)
添加@HimBromBeere所说的内容,如果您选中,您可以看到
Append()
返回具有最新值的IEnumerableappendages@maccettura是的,我明白了:)在英格尔斯索洛的链接中,切多·斯库萨农(chiedo scusaNon ti)全神贯注。谢谢你,我不知道如何正确使用收益率。