List<> .ForEach not found [duplicate]

2020-07-22 17:01发布

问题:

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.