Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

count items in array except value that equal to -1

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?

like image 245
Michael Avatar asked Mar 15 '23 04:03

Michael


2 Answers

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

like image 111
Darren Avatar answered Mar 16 '23 17:03

Darren


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

like image 21
Hamid Pourjam Avatar answered Mar 16 '23 18:03

Hamid Pourjam