简体   繁体   中英

linq - selecting elements not equal to something

Suppose I have a collection of strings. How do I select all the elements that don't contain a certain parameter value?

List<string> TheList = .....

var TheCleanList = (from s in TheList
                    where s != parameter
                    select s).ToList();

I was thinking about where s!= parameter but I'm wondering if there's a cleaner way to do it.

Thanks.

If you don't need a new list you don't need Linq for this - use Remove() - this avoids having to create a new list:

If you want to remove all strings that are equal to Parameter :

TheList.RemoveAll(s => s == Parameter);

If you want to remove all strings that contain Parameter (not clear from your question):

TheList.RemoveAll(s => s.Contains(Parameter));

You mean:

List<string> TheList = ..... 

var TheCleanList = (from s in TheList 
                    where !s.Contains(parameter)
                    select s).ToList();

You can use String.Contains

var TheCleanList = (from s in TheList
                    where !s.Contains(parameter)
                    select s).ToList();

Or

var TheCleanList = TheList.Where(s => !s.Contains(parameter)).ToList();

String.Contains is case-sensitive. If you want a case-insensitve:

string lower = parameter.ToLower();
...
where s.ToLower().Contains(lower)

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