Diego Slinger
Diego Slinger

Reputation: 149

Count elements that match a condition with LINQ

I've tried to use the code from How to count the number of elements that match a condition with LINQ It works but I always have the result equal to a quantity of elements in my list. There are 10 dates on my list and get 10 as the result. I need to count elements with a certain date.

var zz = both.ToList(); // dates list
int con = list1.Where(p => list1.Contains(zz[0])).Count();
Console.WriteLine("count: " + con);

Upvotes: 2

Views: 2160

Answers (1)

Ousmane D.
Ousmane D.

Reputation: 56469

you're using list twice within your code both as the source of the Where clause as well as the source for the Contains method hence it gives unexpected results. rather it should be:

int con = list1.Where(p => zz.Contains(p)).Count();

instead of:

int con = list1.Where(p => list1.Contains(zz[0])).Count();

Upvotes: 3

Related Questions