没有结果时如何在 Linq 中执行 "Select"

How to do a "Select" in Linq when there is no result

假设我有一个包含 3 个元素的列表:

List<int> a = new List<int>{ 1, 2, 3};
a.Select(myFunction);

第二行对列表中的每个元素运行 "myFunction"。 Select 需要 return 类型。是否有类似于 "select" 的扩展方法,但不会 return 任何东西?也就是说,我可以给它一个 "void" 函数吗?

(是的,我知道我可以简单地 foreach)

如果没有内置这样的功能,能否请您帮忙实现一下?

您可以使用List<T>.ForEach方法:

List<int> a = new List<int>{ 1, 2, 3};
a.ForEach(myFunction);

你要找的绝对是System.Collections.Generic命名空间中的List<T>.ForEach(Action<T>)方法

示例:

void Main()
{
    List<int> data = new List<int>() {1,2,3,4};

    data.ForEach(x => print(x));

}
private static void print(int number)
{
    number.Dump();
}

如果你想坚持使用 Enumerable.Select(即使用 IEnumerable<T> 序列)- 只需将 lambda 和 return 函数中的任何内容包装起来:

a.Select(x => { myFunction(x); return true;});