如何基于多个条件并使用linq从通用列表中删除项目 [英] How do I remove items from generic list, based on multiple conditions and using linq

查看:32
本文介绍了如何基于多个条件并使用linq从通用列表中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表,一个包含url,另一个包含所有MIME文件扩展名.我想从第一个列表中删除所有指向此类文件的网址.

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.

示例代码:

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

但是,我的第二个列表中有超过190个扩展名.

However, there are more than 190 extensions in my second list.

问题-我可以用一个衬纸从第一个列表中删除项目,还是唯一使用foreach循环的方法?

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

如果要从源中实际删除项目,则应使用RemoveAll:

If you want to actually remove items from source, you should use RemoveAll:

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

这篇关于如何基于多个条件并使用linq从通用列表中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆