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

后端 未结 2 986
有刺的猬
有刺的猬 2021-01-11 10:48

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.

Sampl

相关标签:
2条回答
  • 2021-01-11 11:44

    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)));
    
    0 讨论(0)
  • 2021-01-11 11:45

    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

    0 讨论(0)
提交回复
热议问题