将两个LINQ查询合并为一个

Sal*_*ari 0 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 };
Run Code Online (Sandbox Code Playgroud)

slo*_*oth 10

你可以使用Concat:

var something = numberGroupsTimes5.Concat(numberGroupsTimes4);
Run Code Online (Sandbox Code Playgroud)

简单地连接两个序列.


为什么你使用a GroupBy,然后过滤器并不完全清楚Key == 0.Remainder永远都是0.

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

var something = numbers.Where(x => x%4 == 0 || x%5 == 0);
Run Code Online (Sandbox Code Playgroud)

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

var result = new[] {4, 5}
             .Select(d => new 
                    { 
                        Divider = d, 
                        Values = numbers.Where(n => n % d == 0).ToList()
                    });
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述