简体   繁体   中英

Select items from List<>

I have this List defined as property :

List<string> colors= new List<string>(); 
colors.Add("Red"); 
colors.Add("Blue"); 
colors.Add("Green");
colors.Add("Black");

And I have this function:

private List<string> getColors(string colorName , List<string> headers)
{
     List<string> list2return = colors(return all colors except red and black);
     return list2return ;
}

My question is how can I select from list all items except red and black ?

Like this?:

colors.Where(c => !c.Equals("Red") && !c.Equals("Black")).ToList()

Or, if you need it to be case-insensitive:

colors.Where(c =>
    !c.Equals("Red", StringComparison.InvariantCultureIgnoreCase) &&
    !c.Equals("Black", StringComparison.InvariantCultureIgnoreCase)
).ToList()

(Though it's not really clear why that method has parameters which aren't being used. Or how it has access to the colors variable in the first place, since that really doesn't look like a class-level member.)

另一种方式是这样的:

colors.Except(new[] { "Red", "Black" });

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