public void Linq40()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var numberGroups =
from n in numbers
group n by n % 5 into g
select new { Remainder = g.Key, Numbers = g };
foreach (var g in numberGroups)
{
Console.WriteLine("Numbers with a remainder of {0} when divided by 5:",
g.Remainder);
foreach (var n in g.Numbers)
{
Console.WriteLine(n);
}
}
}
纯粹的c#等价物是什么?我明白了......
var numberGroups = numbers.GroupBy(n => n % 5)...
但是into
条款有点神秘,我无法弄清楚如何从Key
获取Select
。
答案 0 :(得分:8)
numbers.GroupBy(n => n % 5).Select(g => new { Remainder = g.Key, Numbers = g });
答案 1 :(得分:8)
GroupBy返回IEnumerable<T>
<IGrouping<TKey, TSource>
。这样,您可以执行第二次Select操作,返回与上面完全相同的值:
var numberGroups = numbers.GroupBy(n => n % 5)
.Select(g => new { Remainder = g.Key, Numbers = g });