List<> .ForEach not found [duplicate]

倖福魔咒の 提交于 2019-12-21 20:46:54

问题


I am porting a Windows Phone app to Win 8, and I have found this stumbling block, but cant find the solution.

I have a:

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

and

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

I have added items to my tempItems etc, so then I do this:

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

But I get this error:

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?) 

Why could that be, does Win8 not have this function? I am referencing the following:

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;

If ForEach is not available, is there an alternative that does the same?


回答1:


According to the MSDN entry, ForEach is not available in windows store apps (notice the small icons behind the members).

That being said, the ForEach method is generally not very much more helpful than simply using a foreach loop. So your code:

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

would become:

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

I would argue that in terms of expressiveness it doesn't matter really.



来源:https://stackoverflow.com/questions/15449160/list-foreach-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!