我正在学习c#,我遇到了一个问题,试图在List上使用foreach循环。它一直说“项目”不存在。这是代码:
static int SumOf(List<int> nums)
{
int total = 0;
List<int> theList = new List<int>(nums);
theList.ForEach(int item in theList){
if (item % 2 == 0)
{
total += item;
}
}
return total;
}
foreach方法应该遍历列表并将偶数加到总数中。
你使用的ForEach
是一个List
方法,需要一个Action
。
我想你想要的是使用foreach
关键字的foreach
循环
foreach (int item in theList)
{
if (item % 2 == 0)
{
total += item;
}
}
当然,如果你想以ForEach
的方式做到这一点:
theList.ForEach((item) =>
{
if (item % 2 == 0)
{
total += item;
}
});
ForEach
方法采用Action
(收到一个int)=>(如果是偶数,加总数)
并在列表的每个元素上调用此Action
,因此最终结果应与使用foreach
循环相同。
既然你正在学习C#,我想这篇文章是对动作的一个很好的解读。
https://docs.microsoft.com/en-us/dotnet/api/system.action?view=netframework-4.8
这是ForEach的文档。
如果要使用扩展方法ForEach,则需要使用Action,因此您可以直接访问列表项,如下所示:
theList.ForEach(item => total = item % 2 == 0 ? total + item : total);
或者你可以使用如下的foreach
循环列表项:
foreach(var item in theList)
{
if (item % 2 == 0)
{
total += item;
}
}
foreach(type variableName in IEnumerable<T>)
和List<T>.ForEach(Action<T>)
是不同的。第一个是C#语法循环任何IEnumerable<T>
实例(包括List<T>
),第二个是List<T>
的方法。你可以循环一个列表
static int SumOf(List<int> nums)
{
nums = nums ?? throw new ArgumentNullException(nameof(nums)); // C# 7 syntax for check the nums is null
int total = 0;
foreach(var item in nums)
{
total += item;
}
return toal;
}
要么
static int SumOf(List<int> nums)
{
nums = nums ?? throw new ArgumentNullException(nameof(nums)); // C# 7 syntax for check the nums is null
int total = 0;
nums.ForEach(item=>total += item;)
return toal;
}
或使用Linq
扩展方法
using System.Linq;
static int SumOf(List<int> nums)
{
nums = nums ?? throw new ArgumentNullException(nameof(nums)); // C# 7 syntax for check the nums is null
return nums.Sum()
}