简体   繁体   中英

How do I remove items from generic list, based on multiple conditions and using linq

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?

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)));

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM