List(T).ForEach is not defined using Xamarin

2020-06-03 06:04发布

问题:

I got some code from a friend of mine and it works great in a windows. forms application. When I try to use the same Code in a Xamarin.Forms project, it says:

System.Collections.Generic.List>' has no definition for 'ForEach'. [...] (maybe a "using" is missing) (translated from german))

I have:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Xamarin.Forms;
using System.Reflection;

Here is the Code that gives the error:

public Company GetCompanyById(int companyId) {
        Company company = new Company();

        allContinents
             .MyContinents
             .Select(x => x.Countries)
             .ToList()
             .ForEach(countryList => {
                 countryList.ForEach(country => {
                     country.Cities.ForEach(city => {
                         city.Companies.ForEach(com => {
                             if (com.Id.Equals(companyId))
                                 company = com;
                         });
                     });
                 });
             });
        return company;
    }

Why doesn't it work as is does in a windows.forms app? ps: it's the first ForEach with is underlined in blue

Thanks

回答1:

You're using the Portable Class Library subset of .NET; that doesn't include List<T>.ForEach.

Personally I'm not keen on this approach anyway - it would be much more readable IMO to use LINQ to select the right company. After all, you're performing a query...

return allContinents.MyContinents
                    .SelectMany(x => x.Countries)
                    .SelectMany(c => c.Cities)
                    .SelectMany(c => c.Companies)
                    .First(c => c.Id == companyId);


回答2:

If you can't do without it, you can define your own ForEach extension method

public static class IEnumerableExtensions
{
    public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
    {
        foreach(T item in enumeration)
        {
            action(item);
        }
    }
}