如何根据多个条件并使用linq从通用列表中删除项目

时间:2022-03-08 23:07:39

I have two lists, one containing urls and another, containing all MIME file extensions. I want to remove from the first list all urls that point to such files.

我有两个列表,一个包含URL,另一个包含所有MIME文件扩展名。我想从第一个列表中删除所有指向此类文件的URL。

Sample code:

示例代码:

List<string> urls = new List<string>();
urls.Add("http://*.com/questions/ask");
urls.Add("http://*.com/questions/dir/some.pdf");
urls.Add("http://*.com/questions/dir/some.doc");

//total items in the second list are 190
List<string> mime = new List<string>();
mime.Add(".pdf"); 
mime.Add(".doc"); 
mime.Add(".dms"); 
mime.Add(".dll"); 

One way to remove multiple items is:

删除多个项目的一种方法是:

List<string> result = urls.Where(x => (!x.EndsWith(".pdf")) && (!x.EndsWith(".doc")) && (!x.EndsWith(".dll"))).ToList();

However, there are more than 190 extensions in my second list.

但是,我的第二个列表中有超过190个扩展。

The question - can I remove the items from the first list with a one liner or is using a foreach loop the only way?

问题 - 我可以使用单行删除第一个列表中的项目,还是仅使用foreach循环?

2 个解决方案

#1


15  

If you want to create a new list with only the items matching your condition:

如果要创建仅包含符合条件的项目的新列表:

List<string> result = urls.Where(x => !mime.Any(y => x.EndsWith(y))).ToList();

If you want to actually remove items from source, you should use RemoveAll:

如果要从源中实际删除项目,则应使用RemoveAll:

urls.RemoveAll(x => mime.Any(y => x.EndsWith(y)));

#2


9  

here is a one liner that fits your needs

这是一个适合您需求的衬垫

urls.RemoveAll(x => mime.Any(y => x.EndsWith(y)));

maybe this is a safer appraoach

也许这是一个更安全的appraoach

urls.RemoveAll(x => mime.Contains(Path.GetExtension(x)));

When you have URLs like http://*.com/questions/dir/some.ashx?ID=.pdf you should think about another approach

如果你有像http://*.com/questions/dir/some.ashx?ID=.pdf这样的网址,你应该考虑另一种方法

#1


15  

If you want to create a new list with only the items matching your condition:

如果要创建仅包含符合条件的项目的新列表:

List<string> result = urls.Where(x => !mime.Any(y => x.EndsWith(y))).ToList();

If you want to actually remove items from source, you should use RemoveAll:

如果要从源中实际删除项目,则应使用RemoveAll:

urls.RemoveAll(x => mime.Any(y => x.EndsWith(y)));

#2


9  

here is a one liner that fits your needs

这是一个适合您需求的衬垫

urls.RemoveAll(x => mime.Any(y => x.EndsWith(y)));

maybe this is a safer appraoach

也许这是一个更安全的appraoach

urls.RemoveAll(x => mime.Contains(Path.GetExtension(x)));

When you have URLs like http://*.com/questions/dir/some.ashx?ID=.pdf you should think about another approach

如果你有像http://*.com/questions/dir/some.ashx?ID=.pdf这样的网址,你应该考虑另一种方法