Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

list

lambda

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?

like image 244
TH Todorov Avatar asked May 29 '15 06:05

TH Todorov


People also ask

How to remove item from List based on condition in c# LINQ?

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.


2 Answers

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)));
like image 118
MarcinJuraszek Avatar answered Oct 19 '22 21:10

MarcinJuraszek


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

like image 36
fubo Avatar answered Oct 19 '22 21:10

fubo