日期:2014-05-17  浏览次数:20818 次

关于List.RemoveAll()问题

RecipeModel model = (RecipeModel)listBoxForRecipe.SelectedItem;
            //model.ListForFood.ToList().RemoveAll(f => f.IsChecked == true);
            model.ListForFood = model.ListForFood.ToList().FindAll(f => f.IsChecked == false).ToObservableCollection();

我通过查找ListForFood这个泛型的IsChecked 来决定是否删除,
问题是RemoveAll(f => f.IsChecked == true)这个方法执行成功,我测试过RemoveAll(f => f.IsChecked == true)的返回值,返回的确实是符合条件的个数。
可ListForFood的值却没有删掉,Count不变。
通过FindAll(f => f.IsChecked == false)同样可以实现,不过太不方便了。

------解决方案--------------------
为什么要.ToList()?
生成一个新的对象,你操作的都是新生成的。
我觉得你有必要从基础学起,免得将来地基不牢出事故。
------解决方案--------------------
这么写
RemoveAll(f => {return f.IsChecked == true;}),例子

 List<string> l = new List<string>() { "A1", "A2", "A3", "B1", "B2", "B3" };
            int cl = l.RemoveAll(x => { return x.Contains("A"); });
            l.ForEach(x => Console.WriteLine(x));

------解决方案--------------------
引用:
为什么要.ToList()?
生成一个新的对象,你操作的都是新生成的。
我觉得你有必要从基础学起,免得将来地基不牢出事故。


+1