Question

I have this lambda expression:

if (!myList.Any( x => x.name == "example" && x.articleNumber == "1"))
{

}
else
{

}

myList contains an object from the class which has these properties: articleNumber, name and quantity.

And this enters in the if instead of in the else althought there is an object with name "example" AND articleNumber "1". Why does this happen?

Was it helpful?

Solution 2

The only reason i can see is that there's no element with name=="example" and articleNumber=="1". Note that the == operator is case sensitive in C# and that there might be a white-space somewhere.

Then you can use this overload of Equals to compare case-insensitive and remove white-spaces with Trim:

if (!myList.Any( x => x.name.Trim().Equals("example", StringComparison.OrdinalIgnoreCase) 
                   && x.articleNumber == "1"))
{

}
else
{

}

You should also consider to change the type of articleNumber to int since it is a number.

OTHER TIPS

You are aware of the ! before your lamda right?

what you are asking in the if statement is

If myList does NOT contain any values where name is example AND article number is 1

I don't know if this helps but maybe it's easier to answer if you supply more information about what you want to accomplish with the statement.

I'm pretty sure that the list don't contain the entry you think it does. Set a debug marker on the if line, and inspect the list at that point to see what it contains. You will find that the entry is not there. Remember that strings are case sensitive as well, so if name really is Example, it will not match.

Your list probably contains some values that you don't expect.

Try to replace && with || and see what you will get:

var v = myList.Where(x => x.name == "example" || x.articleNumber == "1").ToList();

just to see what's there .

Nothing wrong with your logic but you counld try??

if (myList.Where( x => x.name == "example").Where(x=> x.articleNumber == "1").Count() > 0)
{

}
else
{

}

OR to remove all spaces and variances in Casing

if (!myList.Any( x => x.name.Trim().ToLower() == "example" && x.articleNumber.Trim().ToLower() == "1"))
{

}
else
{

}

The definition of Any: Determines whether any element of a sequence exists or satisfies a condition.

So for each element in a sequence it is determined if the predicate is matching your expression.

myList.Any( x => x.name == "example" && x.articleNumber == "1")

Will return true if ANY element of the List has the name "example" AND the articleNumber 1.

!myList.Any( x => x.name == "example" && x.articleNumber == "1")

Will return true if NO element of the List has the name "example" AND the articleNumber 1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top