Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List(T).ForEach is not defined using Xamarin

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

like image 935
Hendrik Avatar asked Oct 22 '14 08:10

Hendrik


2 Answers

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);
like image 66
Jon Skeet Avatar answered Nov 11 '22 21:11

Jon Skeet


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);
        }
    }
}
like image 28
Stuart Avatar answered Nov 11 '22 19:11

Stuart