【发布时间】:2022-11-23 22:53:19
【问题描述】:
只是想知道如果在扩展方法内部调用 Select 调用为什么不会执行? 还是我认为 Select 只做一件事,而它的目的是不同的?
代码示例:
var someList = new List<SomeObject>();
int triggerOn = 5;
/* list gets populated*/
someList.MutateList(triggerOn, "Add something", true);
MutateList 方法声明:
public static class ListExtension
{
public static IEnumerable<SomeObject> MutateList(this IEnumerable<SomeObject> objects, int triggerOn, string attachment, bool shouldSkip = false)
{
return objects.Select(obj =>
{
if (obj.ID == triggerOn)
{
if (shouldSkip) shouldSkip = false;
else obj.Name += $" {attachment}";
}
return obj;
});
}
}
没有 Select 的解决方案有效。我只是在做一个 foreach。
我知道 Select 方法有一个摘要:“将序列的每个元素投影到新形式中。”但如果那是真的,那么我的代码示例不会显示错误吗?
我使用的解决方案(在 MutateList 方法内部):
foreach(SomeObject obj in objects)
{
if (obj.ID == triggerOn)
{
if (shouldSkip) shouldSkip = false;
else obj.Name += $" {attachment}";
}
});
return objects;
【问题讨论】:
-
请注意
Select返回一个新的枚举。它不会修改它操作的可枚举。 -
“选择调用不会执行” - 你是如何检查它没有被执行的?
-
“没有 Select 的解决方案有效。” - 哪个解决方案没有选择?没有显示这样的解决方案。
-
@ThomasWeller 我有点小气,显示了列表的位置是突变(磨碎它是列表中的项目而不是列表本身)
-
@ThomasWeller 我用解决方案更新了问题。我通过在 Select 中添加一个断点来测试它。
标签: c# select ienumerable