将两个LINQ查询合并为一个

时间:2015-07-22 09:22:44

标签: c# linq

我想将整数数组排序为2组(4组组和5组组)。我想知道如何只使用一个查询来做同样的事情:

int[] numbers = { 2, 7, 8, 10, 12, 14, 19, 25 };

var numberGroupsTimes5 =
    from n in numbers
    group n by n % 5 into g
    where g.Key == 0
    select new { Remainder = g.Key, Numbers = g };

var numberGroupsTimes4 =
    from n in numbers
    group n by n % 4 into g
    where g.Key == 0
    select new { Remainder = g.Key, Numbers = g };

4 个答案:

答案 0 :(得分:10)

您可以使用Concat

sudo sh -c 'rm /var/log/jenkins/*'

简单地连接两个序列。

为什么您使用var something = numberGroupsTimes5.Concat(numberGroupsTimes4); ,然后过滤GroupBy并不完全清楚。 Key == 0始终为Remainder

也许一个简单的0就足够了? 您可以使用逻辑OR(Where)简单地“合并”您的查询:

||

回应你的评论:你在找这样的东西吗?

var something = numbers.Where(x => x%4 == 0 || x%5 == 0);

enter image description here

答案 1 :(得分:1)

你的意思是?

var numberGroupsTimes4or5 =
    from n in numbers
    group n by n into g
    where g.Key % 4 == 0 || g.Key % 5 == 0
    select new { Remainder = g.Key, Numbers = g };

答案 2 :(得分:1)

也许是吗?

var result = new[] { 4, 5 }
            .SelectMany(x => numbers.Select(n => (n, x)))
            .Where(g => g.n % g.x == 0)
            .GroupBy(g => g.x, (Key, g) => 
                    new { Remainder = Key, Numbers = g.Select(z => z.n) });

给出此结果

enter image description here

这是一种类似的方法,但是这次使用的查询语法类似于您的问题。

var numbersAndRemainders = new[] { 4, 5 }
            .SelectMany(rem => numbers.Select(n => (n, rem)));

        var numberGroups =
            from n in numbersAndRemainders
            group n by new { remainder = n.n % n.rem, n.rem } into g
            where g.Key.remainder == 0
            select new { Remainder = g.Key.rem, Numbers = g.Select(z => z.n) };

答案 3 :(得分:0)

您可以使用两种Linq方法:

//This will join the lists, excluding values that already appear once
var result = numberGroupsTimes5.Union(numberGroupsTimes4)

//This will simply append one list the the other
var result = numberGroupsTimes5.Concat(numberGroupsTimes4)