How do I remove items from generic list, based on

2020-03-10 05:44发布

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.

Sample code:

List<string> urls = new List<string>();
urls.Add("http://stackoverflow.com/questions/ask");
urls.Add("http://stackoverflow.com/questions/dir/some.pdf");
urls.Add("http://stackoverflow.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.

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

2条回答
一夜七次
2楼-- · 2020-03-10 06: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:

urls.RemoveAll(x => mime.Any(y => x.EndsWith(y)));
查看更多
戒情不戒烟
3楼-- · 2020-03-10 06:18

here is a one liner that fits your needs

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

maybe this is a safer appraoach

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

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

查看更多
登录 后发表回答