Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use an embedded lambda with the Contains method?

I want to filter a list with FindAll

If I write:

.FindAll(
    p => p.Field == Value && 
    p.otherObjList.Contains(otherObj));

it's ok, but if I write

.FindAll(
    p => p.Field == Value && 
    p.otherObjList.Contains(
        q => q.Field1 == Value1 && 
        q.Field2 == Value2));

I get C# syntax error message: Unknown Method FindAll(?) of .. the otherObjList

I cannot define the otherObj exactly, because I know only the values of two fields, Field1 and Field2.

What have I done wrong? What can I do in this case?

like image 585
mikeM Avatar asked May 23 '11 21:05

mikeM


People also ask

Can lambda expression contain statements?

In particular, a lambda function has the following characteristics: It can only contain expressions and can't include statements in its body. It is written as a single line of execution.

Can Lambda contain if?

Since a lambda function must have a return value for every valid input, we cannot define it with if but without else as we are not specifying what will we return if the if-condition will be false i.e. its else part.

When should Lambda not be used?

You do not want to use Lambda for long-running workloads because it runs instances/functions for up to 15 minutes at a time. It limits concurrent function executions to 1,000. AWS Lambda bills can quickly run through your budget if you are unsure how to optimize AWS costs.

Can the lambda expression in Python contain a block of multiple statements?

You cannot write multiple statements in the body of a lambda function. 4. We call the function and print the returned value.


1 Answers

The Contains() method for both most collection types as well as the LINQ version expects an argument of the same type as the collection, not a lambda.

It appears you are just trying to check if any item matches some condition. You should use the Any() method.

.FindAll(p => p.Field == Value
           && p.otherObjList.Any(q => q.Field1 == Value1 && q.Field2 == Value2))
like image 189
Jeff Mercado Avatar answered Sep 30 '22 04:09

Jeff Mercado