【问题标题】:List<> .ForEach not found [duplicate]List<> .ForEach 未找到 [重复]
【发布时间】:2013-03-16 12:18:19
【问题描述】:

我正在将 Windows Phone 应用程序移植到 Win 8,我找到了这个绊脚石,但找不到解决方案。

我有一个:

 List<items> tempItems = new List<items>();

ObservableCollection<items> chemists = new ObservableCollection<items>();

我已将项目添加到我的 tempItems 等,所以我这样做:

  tempItems.OrderBy(i => i.Distance)
                .Take(20)
                .ToList()
                .ForEach(z => chemists.Add(z));

但我收到此错误:

Error   1   'System.Collections.Generic.List<MyApp.items>' does not contain a definition for 'ForEach' and no extension method 'ForEach' accepting a first argument of type 'System.Collections.Generic.List<MyApp.items>' could be found (are you missing a using directive or an assembly reference?) 

为什么会这样,Win8没有这个功能吗?我引用以下内容:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Xml.Linq;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Imaging;
using Windows.UI.Xaml.Navigation;
using System.Collections.ObjectModel;

如果 ForEach 不可用,是否有替代方法可以做到这一点?

【问题讨论】:

  • 如果还没有,请检查项目的目标框架实际上是 .net 4.5,而不是客户端配置文件或类似的东西。我怀疑 ForEach 在 Win8 中不可用,但这只是一个猜测,因此它在评论中。
  • 普通的 foreach 循环有什么问题?这将解决您在两种环境中的问题。
  • @ErikvanBrakel 虽然您提出了一个有效的观点,但似乎 ForEach() 确实可用并且 OP 可能在某处存在配置或设置问题,他想解决它。
  • @DavidKhaykin 这就是为什么我没有把它变成答案并将其放入 cmets ;-) 但你是对的,可能某处有问题......
  • 哇。根据这个问题和接受的答案,它实际上在 Metro 风格的应用程序中消失了 - stackoverflow.com/questions/10299458/…

标签: c# windows-8 windows-store-apps .net-4.5


【解决方案1】:

根据MSDN entry,Windows 商店应用程序中不提供 ForEach(注意成员后面的小图标)。

话虽如此,ForEach 方法通常并不比简单地使用 foreach 循环更有帮助。所以你的代码:

tempItems.OrderBy(i => i.Distance)
         .Take(20)
         .ToList()
         .ForEach(z => chemists.Add(z));

会变成:

var items = tempItems.OrderBy(i => i.Distance).Take(20);
foreach(var item in items)
{
    chemists.Add(item);
}

我认为就表现力而言,这并不重要。

【讨论】:

  • 这很好,感谢我所追求的
  • 或者为什么不简单地使用AddRange 方法(假设您的目标集合支持它)?
  • 或者自己写扩展方法stackoverflow.com/a/200584/901059
  • @mydogisbox 我考虑过,但据我发现 ObservableCollection 不支持 AddRange。
猜你喜欢
  • 2014-04-14
  • 1970-01-01
  • 2015-11-24
  • 1970-01-01
  • 1970-01-01
  • 2016-08-27
  • 2021-06-22
  • 2019-06-23
  • 1970-01-01
相关资源
最近更新 更多