Wes Doyle
Wes Doyle

Reputation: 2287

How to parameterize a boolean expression in Linq?

I have a Linq statement that looks something like:

Report.Where(a=>a.Property == 1 || a.Property == 2 || a.Property == 3).Count()

I would like to know if I can refactor the statement into something of the form:

Report.Where(a=a.Property == validProperties)

where I can store a set of validProperties as an array of integers.

Upvotes: 2

Views: 71

Answers (1)

Shyju
Shyju

Reputation: 218812

You can use Contains method

var idsToCheck = new List<int> {1,2,3};

var someCount = Report.Where(a=>idsToCheck.Contains(a.Property)).Count();

Or call the Count first and pass the lambda expression to that.

var someCount = Report.Count(a => idsToCheck.Contains(a.Property));

Upvotes: 4

Related Questions