如何使用LINQ将奇数和偶数进行分组? [英] How can I group odd and even using LINQ?

查看:50
本文介绍了如何使用LINQ将奇数和偶数进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用LINQ将我的奇数和偶数分组到两个单独的数组中.

I'd like to use LINQ to group my odd and even numbers in two separate arrays.

 int[] randNum = randomNums(20, 1000, 1000);
 var oddEvnNums = from num in randNum
                  group ???
                  select new { odd = oddNums[], even = evnNums[]}


 int oddNum = oddEvnNums.odd[0];
 int evenNum = oddEvnNums.even[0];

推荐答案

只需创建一个键为 num&的查找即可.1 (对于正数,等于 num%2 ,但对于负数,则坚持1而不是-1):

Just create a lookup with a key of num & 1 (equivalent to num % 2 for positive numbers, but sticking with 1 instead of -1 for negative numbers):

var lookup = randNum.ToLookup(num => num & 1);
var even = grouped[0].ToArray();
var odd = grouped[1].ToArray();

请注意,如果您要求没有任何条目的键,则查找将返回空序列,因此您无需担心 是否为奇数和偶数数字.

Note that a lookup will return an empty sequence if you ask for a key which doesn't have any entries, so you don't need to worry about whether or not there are odd and even numbers.

或者,除了分组之外,您可能还可以遍历整个序列两次:

Alternatively, instead of grouping, you could just potentially go through the whole sequence twice:

var even = randNum.Where(num => (num & 1) == 0).ToArray();
var odd = randNum.Where(num => (num & 1) == 1).ToArray();

这仅在两次序列相同时才有效(例如,而不是每次迭代都随机生成),但它可能比分组方法更有效.

That only works if the sequence is the same both times (rather than being randomly generated each time you iterate, for example) but it may be more efficient than the grouping approach.

这篇关于如何使用LINQ将奇数和偶数进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆