名称“item”在当前上下文中不存在

问题描述 投票:0回答:3

我正在学习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方法应该遍历列表并将偶数加到总数中。

c# visual-studio asp.net-core scope
3个回答
4
投票

你使用的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的文档。

https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.foreach?view=netframework-4.8


0
投票

如果要使用扩展方法ForEach,则需要使用Action,因此您可以直接访问列表项,如下所示:

theList.ForEach(item => total = item % 2 == 0 ? total + item : total);

或者你可以使用如下的foreach循环列表项:

foreach(var item in theList) 
{
    if (item % 2 == 0)
    {
        total += item;
    }
}

0
投票

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()
}

© www.soinside.com 2019 - 2024. All rights reserved.