Lai32290
Lai32290

Reputation: 8548

Double filter with lambda expression

I'm creating a product edit form in WPF. This form has text boxes for the following properties: Id, Code, Width, Height, and Color.

Id and Code cannot repeat, so I want make a "checking" for Code repeat in my Code_TextChanged event.

I have tried the following lambda expression for checking:

// List<Product> products = …;
if (products.Where(x => x.code.Equals(Code.Text))
            .Count(g => !g.id.Equals(Id.Text)) > 0)
    CodeExist = true;

I don't know why, when I opened a register, it will mark CodeExist as true.

How to I can make a condition, for filter product.code.Equals(Code.Text) and !product.id(Id.Text)?

Upvotes: 0

Views: 2698

Answers (1)

htxryan
htxryan

Reputation: 2961

You can add multiple conditions using "&&" (which is equivalent to "AND" in SQL) or "||" (which is equivalent to "OR" in SQL).

You can also use the LINQ "Any()" method to return true if one or more elements in the collection match a condition.

So your if statement would read:

if(products.Any(x=>x.code.Equals(Code.Text) && !x.id.Equals(Id.Text))){
     CodeExists = true;
}

EDIT: Fixed minor typo with "!" placement.

Upvotes: 3

Related Questions