列表与LT;> .ForEach没找到

时间:2013-03-16 12:18:19

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

我正在将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不可用,是否有其他方法可以做同样的事情?

1 个答案:

答案 0 :(得分:15)

根据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);
}

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