怎么用.RemoveAll在这里?

时间:2014-07-31 20:34:36

标签: c# asp.net removeall

这里有一个简单的问题,但这一直在杀我试图让这个工作......

我有一个名为Taxonomy的课程。有一个名为WebName的属性,我得到了Taxonomy个类的列表,并希望.RemoveAll使用WebName.ToLower()删除列表中的任何分类法等于"n/a""other"WebName属性的类型为字符串。

这是我到目前为止所尝试的:

List<Taxonomy> theNeighborhoods = new List<Taxonomy>();
Taxonomy aNeighborhood = GetCachedNeighborhoodTaxonomy(); // Returns the Parent Taxonomy

theNeighborhoods = aNeighborhood.Children.ToList(); // This gives me a list of Taxonomy classes

如何将theNeighborhoods列表更改为仅选择每个WebName的{​​{1}}属性中没有“n / a”或“other”的值?

Taxonomy

上面的代码给出了错误,例如theNeighborhoods = aNeighborhood.Children.ToList().RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other").ToList(); 没有扩展程序int如何使用ToList执行此操作?

3 个答案:

答案 0 :(得分:4)

试试这个:

theNeighborhoods = aNeighborhood
                   .Children
                   .Where(a => a.WebName.ToLower() != "n/a" &&
                               a.WebName.ToLower() != "other")
                   .ToList();

您的代码无效,因为RemoveAll会返回int而不是List<T>IEnumerable<T>

另外值得注意的是,您曾两次致电ToListToList并非免费。它涉及创建新数组和复制项目。因此,请避免多余使用ToList

答案 1 :(得分:2)

你可以做两件事之一。首先,您可以使用LINQ中的位置:

theNeighborhoods = aNeighborhood.Children.Where(a => a.WebName.ToLower() != "n/a" && a.WebName.ToLower() != "other").ToList();

或者你可以在获得列表后调用RemoveAll,如下所示:

theNeighborhoods = aNeighborhood.Children.ToList();
theNeighborhoods.RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other").ToList();

RemoveAll返回一个int,表示删除了多少项。这就是你得到错误的原因。我建议查看RemoveAll上的文档。

答案 2 :(得分:0)

仅限尝试:

aNeighborhood.Children.ToList().RemoveAll(a => a.WebName.ToLower() == "n/a" || a.WebName.ToLower() == "other");

你不能写ToList(),因为RemoveAll返回删除的元素数(int)。