Dylan Gomes
Dylan Gomes

Reputation: 93

Count does not return the right count properly

I've got a table containing a list of persons, where 5 persons are between the age 12 to 25. Those persons are living in Limburg and are male.

string[] leeftijdstring = new string[2];
int leeftijd1;
int leeftijd2;
int getal = 0;
if (leeftijd == "null")
{
    leeftijd1 = 0;
    leeftijd2 = 150;
}
else
{
    leeftijdstring = leeftijd.Split('-');
    leeftijd1 = Convert.ToInt32(leeftijdstring[0]);
    leeftijd2 = Convert.ToInt32(leeftijdstring[1]);
}
var count = (from p in _db.Personen
    join pc in _db.Postcodes on p.Postcode equals pc.postcode
    join r in _db.Regios on pc.RegioId equals r.RegioId
    where (p.Leeftijd >= leeftijd1 && leeftijd2 <= p.Leeftijd) &&
    r.RegioNaam == regio && p.Geslacht == geslacht
    select p.PersoonId).Distinct().Count();

Anyway, count returns 0 for me, but there should be at least 4 really matching the search!

My table look like the following:

Personen:

Upvotes: 0

Views: 92

Answers (1)

Alex
Alex

Reputation: 13224

It appears that this is where your error is:

where (p.Leeftijd >= leeftijd1 && leeftijd2 <= p.Leeftijd)

For example, lets take:

leeftijd1 = 0;
leeftijd2 = 150;

And evaluate:

where (p.Leeftijd >= 0 && 150 <= p.Leeftijd)    

This will only return true if p.Leeftijd >= 150.

You need to change this to:

where (p.Leeftijd >= leeftijd1 && p.Leeftijd <= leeftijd2)

There is one more clear bug in your code (I think): if (leeftijd == "null") should be if (string.IsNullOrWhiteSpace(leeftijd)).

Upvotes: 2

Related Questions