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?
C# | Remove all elements of a List that match the conditions defined by the predicate. List<T>. RemoveAll(Predicate<T>) Method is used to remove all the elements that match the conditions defined by the specified predicate.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With