简体   繁体   中英

Using more than one condition in linq's where method

I have a line of code using where:

codebase.Methods.Where(x => x.Body.Scopes.Count > 5);

How can I insert more than one condition? So I can say x => predicate && y => predicate ?

Thanks

You can roll your separate conditions into a single predicate if you like:

codebase.Methods.Where(x => (x.Body.Scopes.Count > 5) && (x.Foo == "test"));

Or you can use a separate Where call for each condition:

codebase.Methods.Where(x => x.Body.Scopes.Count > 5)
                .Where(x => x.Foo == "test");

no you can't define 2 delegates in the same where but you can build after each other or put both on same condition like this

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.Scopes.name == "" );

or 

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5 )
        .where( y=> y.Body.Scopes.name == '' );

or 

 var result = codebase.Methods.Where(x => x.Body.Scopes.Count > 5  )
.Union( codebase.Methods.Where(y => y.Body.Scopes.name == ''  ) );

In your example, where does y come from? The Where method takes a lambda with a single input parameter, which represents a single instance of the sequence you're operating against.

You can, of course, have multiple conditions against x :

Where(x => x.Foo > 5 && x.Bar < 3)

What would "y" represent?

You can just use a standard && condition. No need for a "y":

codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.SomethingElse < 14);

I don't get it. What can you not do?

codebase.Methods.Where(x => x.Head.IsHairy && x.Body != null && x.Body.Scopes.Count > 5); 

像这样..

codebase.Methods.Where(x => x.Body.Scopes.Count > 5 && x.Body.Scopes.Count < 10);
codebase.Methods.Where(x => x.Body.Scopes.Count > 5).Where(x => x.Body.Scopes.TypeName == "Scopes").Where(x => x.Body.Scopes.Level == LEVEL_HIGH);

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