如何将这些LINQ语句重写为一个查询

时间:2016-02-26 17:50:33

标签: c# linq

是否可以使用一个LINQ查询来执行相同的操作?

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);

修改:想要获得此

enter image description here

6 个答案:

答案 0 :(得分:4)

Count()已经允许您指定谓词。因此,您可以将上述内容组合在一个linq中:

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

另请注意,它会比执行Where()快得多,因为计数比实际返回匹配元素更容易执行。

修改

如果你想要的只是一个linq查询,你可以做以下聪明的伎俩:

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

答案 1 :(得分:2)

你可以这样做一个查询:

var q = ints.Select(i => new { Number = i, Type = (i % 2 == 0) ? "Even" : "Odd" }).GroupBy(i => i.Type).Select(g => new { Type = g.Key, Count = g.Count() });

这会返回一个列表,但是' Type'和' Count',如下所示。

enter image description here

如果你正在寻找一个像现在这样简单的对象,你可以使用更简单的东西:

var q = new { OddCount = ints.Count(i => i % 2 != 0), EvenCount = ints.Count(i => i % 2 == 0) };

enter image description here

这将是" OddCount"和" EventCount"属性。

答案 2 :(得分:1)

这是另一种只对原始列表进行一次迭代的方法。

var ints = new []{1,2,3,4,5};
string[] parities = { "even", "odd" };

var result = ints
    .GroupBy(i => i % 2)
    .Select(g => new { Name = parities[g.Key], Count = g.Count() });

enter image description here

答案 3 :(得分:1)

听起来像是Aggregate的完美候选人:

var ints = new[] { 1, 2, 3, 4, 5 };

var info = ints.Aggregate(
    new { oddCount = 0, evenCount = 0 }, (a, i) =>
    new { oddCount = a.oddCount + (i & 1), evenCount = a.evenCount + ((i & 1) ^ 1) });

Console.WriteLine(info);

打印

{ oddCount = 3, evenCount = 2 }

答案 4 :(得分:0)

您只需将查询直接移至选择

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

答案 5 :(得分:0)

int odd = 0;
int even = 0;

(from s in ints
        let evens = s % 2 == 0 ? even++ : even
        let odds = s % 2 != 0 ? odd++ : odd
        select true).ToList();

这样你就可以加载偶数和奇数。

这种方法的优点是它只迭代一次数组