Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rewrite these LINQ statements into one query

Tags:

c#

linq

Is it possible to use one LINQ query to do the same?

var ints = new []{1,2,3,4,5};
var odd = from i in ints where i%2==1 select i;
var even = from i in ints where i%2==0 select i;
var q = from s in new[]{""} 
    select new {oddCount = odd.Count(), evenCount = even.Count()};

Console.Write(q);

Edit: Want to get this

enter image description here

like image 998
Rm558 Avatar asked Dec 17 '25 14:12

Rm558


1 Answers

Count() already allows you to specify a predicate. So you can combine the above in one linq like this:

var ints = new[] { 1, 2, 3, 4, 5 };
Console.Write($"Odd={ints.Count(i => i % 2 == 1)}, Even={ints.Count(i => i % 2 == 0)}");

Also note that it will be considerably faster than doing a Where() as counting is easier to perform than actually returning matching elements.

Edit

If all you want is a single linq query, you could do the following clever trick:

var ints = new[] { 1, 2, 3, 4, 5 };
var Odd = ints.Count(i => i % 2 == 1);
Console.Write($"Odd={Odd}, Even={ints.Length - Odd}");
like image 160
dotNET Avatar answered Dec 19 '25 03:12

dotNET



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!