【发布时间】:2013-10-22 07:26:05
【问题描述】:
对于它的价值,我花了一段时间查看下面的相关帖子,除了它在具有多个属性而不是两个独立列表的同一个列表上工作,也不涉及包含比较而不是项目的文本匹配。
我有一个名为“fruits”的满是水果的字符串列表
Apple
Orange
Banana
我还有一个名为 products 的字符串列表,其中包含一些水果(以及其他杂项信息)和一些其他产品。
ShoeFromNike
ApplePie
OrangeDrink
我需要从第二个列表中删除所有项目,其中每个单独的行不包含水果列表中列出的任何项目。
最终结果将是仅包含以下内容的产品列表:
ApplePie
OrangeDrink
我最好的迭代方法:
//this fails becaucse as I remove items the indexes change and I remove the wrong items (I do realize I could reverse this logic and if it meets the criteria ADD it to a new list and i'm sure there's a better way.)
for (int i = 0; i < products.Count(); i++)
{
bool foundMatch = false;
foreach (string fruit in fruits)
if (products[i].Contains(fruit))
foundMatch = true;
if (foundMatch == false)
products.Remove(products[i]);
}
我最好的 lambda 方法:
products.RemoveAll(p => !p.Contains(fruits.Select(f=> f)));
【问题讨论】:
标签: c# linq collections lambda iterator