-3

我有一组电子邮件。我需要使用我的where表达式获取两个数组。

var firstArray = emailTo.Where(e => whiteList.Contains(e.Address));
var secondArray = emailTo.Where(e => !whiteList.Contains(e.Address));

这个怎么做?

PS在我写作的时候,我已经明白了如何做到这一点:

emailTo.ForEach(e => ... use if construction and add to array ... );

也许你有什么解决办法?

4

3 回答 3

8
var twoArrays = emailTo.GroupBy(e => whiteList.Contains(e.Address),
                                (key,g) => g.ToArray())
                       .ToList();

var firstArray = twoArrays[0];
var secondArray = twoArrays[1]; 

注意firstArray以上secondArray内容可能firstArraysecondArray您的代码中的内容不同。那是因为无法确定数组的顺序。为了确保,您可能希望在OrderBy(g=>g.Key)之后追加GroupBy,然后Select像这样:

var twoArrays = emailTo.GroupBy(e => whiteList.Contains(e.Address))
                       .OrderBy(g=>g.Key).Select(g=>g.ToArray())
                       .ToList();   
//Now the firstArray is always at the index 1
var firstArray = twoArrays[1];
var secondArray = twoArrays[0];                         
于 2013-09-03T07:03:17.697 回答
2

你只需要使用Enumerable.ToArray

var firstArray = emailTo.Where(e => whiteList.Contains(e.Address)).ToArray();
var secondArray = emailTo.Where(e => !whiteList.Contains(e.Address)).ToArray();

Side-Note_ 而不是List.ForEach.NET 2.0 循环列表的方法,我将使用简单的foreach. 然后你不需要创建另一个集合。

foreach(var emailTo in firstArray)
{
    // ...
}
于 2013-09-03T07:01:56.897 回答
0
var firstArray = emailTo.Where(e => whiteList.Contains(e.Address)).ToArray();
var secondArray = emailTo.Except(firstArray).ToArray();
于 2013-09-03T07:13:36.393 回答