简体   繁体   中英

c# linq lambda where not

Im following this tutorial about lambda expressions, and created the following code;

Func<int, bool> isHighNUmber = s => s > 10;
IList<int> intList = new List<int>() { 1, 3,9, 2, 63, 236, 32, 474, 83, 832, 58, 3458, 35, 8, 4 };

Console.WriteLine("All numbers.");
foreach (int x in intList)
{
    Console.WriteLine(x);
}
Console.WriteLine("High Numbers");
foreach(int x in intList.Where(isHighNUmber).ToList<int>())
{
    Console.WriteLine(x);
}

And it works fine, now I wanted to try to get the low numbers only, so I tried

foreach(int x in intList.Where(!isHighNUmber).ToList<int>())

foreach(int x in intList.Where(isHighNUmber == false).ToList<int>())

and variations of the above syntax but could not get it to work. I also looked for a function like WhereNot

foreach(int x in intList.WhereNot(!isHighNUmber).ToList<int>())

to replace the where function but could not find a suitable one.I could easily add another Func to do the opposite of isHighNumber but I imagine if that func is very big you would not want to rewrite it completely. How should I get the opposite of a lambda Func in the where method?

Try this:

  foreach(int x in intList.Where(x=> !isHighNUmber(x)).ToList<int>())

You cannot use this syntactic sugar unless you create isNotHighNumber function that negates isHighNumber

I think your only option in that case is to actually invoke the function

foreach (int x in intList.Where(x=>! isHighNUmber(x)).ToList<int>())
{
     Console.WriteLine(x);
}

You could also use Except but it would not be as efficient since it would likely iterate over the sequence twice.

Console.WriteLine("Low Numbers");
foreach (int x in intList.Except(intList.Where(isHighNUmber)).ToList<int>())
{
    Console.WriteLine(x);
}

You should update your Func as shown below:

Func<int, bool, bool> isHighNUmber = (s, isGreaterCheck) => { return isGreaterCheck ? s > 10 :  s <= 10 ;};

and then write foreach as mentioned below:

Console.WriteLine("Low Numbers");
foreach(int x in intList.Where(x => isHighNUmber(x, false)).ToList<int>())
{
    Console.WriteLine(x);
}

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