I have this LINQ to entity:
int siteNumbers = g.Select(x => x.siteId).ToArray().Distinct().Count()
For example:
When x.siteId
is -1
I don't want the value to be counted,i.e I want to count only values that not equal to -1
.
when x:[1,2,6,-1]
then siteNumbers
value is 3.
when x:[-1]
then siteNumbers
value is 0.
What do I have to change in query above to implement it?
You can take advantage of the Where
clause in LINQ
:
int siteNumbers = g.Where(x => x.siteId != -1)
.Select(x => x.siteId)
.Distinct()
.Count();
You can also remove the .ToArray()
as it is redudant.
Working example: https://ideone.com/LvOe0i
Use Where
to filter the result
int siteNumbers = g.Where(x => x.siteId != -1)
.Select(x => x.siteId)
.Distinct()
.Count();
Also calling ToArray
might not be necessary since siteId
is integral and SQL knows who to compare them and get distinct values.
you can also add a condition to Count
int siteNumbers = g.Select(x => x.siteId)
.Distinct()
.ToArray()
.Count(x => x != -1);
you should call ToArray
since Count
overload with predicate is not supported by linq to entities
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With