我从我的一个朋友那里得到了一些代码,它在windows中运行得很好。表格申请。 当我尝试在Xamarin.Forms项目中使用相同的代码时,它说:
System.Collections.Generic.List>”没有'ForEach'的定义。 [...](可能缺少“使用”)(翻译自德语))
我有:
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;
以下是给出错误的代码:
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;
}
为什么它不像windows.forms应用程序那样工作? ps:这是第一个以蓝色
加下划线的ForEach由于
答案 0 :(得分:15)
您正在使用.NET的可移植类库子集;并不包含List<T>.ForEach
。
我个人并不热衷于这种方法 - 使用LINQ来选择合适的公司会更加可读。毕竟,您正在执行查询 ...
return allContinents.MyContinents
.SelectMany(x => x.Countries)
.SelectMany(c => c.Cities)
.SelectMany(c => c.Companies)
.First(c => c.Id == companyId);
答案 1 :(得分:14)
如果你不能没有它,你可以定义自己的ForEach扩展方法
public static class IEnumerableExtensions
{
public static void ForEach<T>(this IEnumerable<T> enumeration, Action<T> action)
{
foreach(T item in enumeration)
{
action(item);
}
}
}