我有一系列清单:
List<foo> spamSpamAndSpam;
List<foo> spamSpamSpamSausageEggsAndSpam;
List<foo> spamSpamSpamSausageEggsBaconAndSpam;
List<foo> spamSpamSpamSpamSpamWithoutSpam;
List<foo> spamSpamSpamSpamSpamSpamSpamSpamSpamLovelySpamWonderfulSpam;
我还在foo
的属性中找到了一系列值:
List<string> Brian= new List<string>();
Brian.Add("Always");
Brian.Add("Look");
Brian.Add("On");
Brian.Add("The");
Brian.Add("Bright");
Brian.Add("Side");
Brian.Add("Of");
Brian.Add("Life");
我正在捕获对所有foo
'ses的引用,其中给定属性(例如,bar
)具有后一个列表中包含的值。我是这样做的:
func<foo, bool> deadParrot = x => Brian.Contains(x.bar);
IEnumerable<foo> okLumberjacks = spamSpamAndSpam.Where(deadParrot);
okLumberjacks = okLumberjacks.Concat(
spamSpamSpamSpamSausageEggsAndSpam.Where(deadParrot));
// And so on, concatenating the results of Where() from every list of <foo>.
我需要在单个foo
中匹配过滤功能的每个IEnumerable<foo>
,以便我可以一次性调用所有这些方法,如下所示:
foreach (foo incontinentRunner in okLumberjacks)
{
incontinentRunner.SillyWalk();
}
所以我的问题是......有没有办法在一个集合中收集每个foo
,而不必诉诸于:
ni = ni.Concat(someList.Where(filter));
我的意思是,是否有更优雅的方式与Linq做这样的事情?我正在寻找类似的东西:
okLumberjacks = spamSpamAndSpam.
And(spamSpamSpamSausageEggsAndSpam).
And(spamSpamSpamSausageEggsBaconAndSpam) /* etc */ .Where(deadParrot);
甚至更好:
okLumberjacks = spanishInquisition.Where(deadParrot);
// Where the type of spanishInquisition is List<List<foo>>.
我不想修改foo
的原始列表,因为我需要它们,因为它们稍后会在代码中进行另一次操作。
答案 0 :(得分:5)
创建列表列表,然后展平它:
List<List<foo>> lists = new List<List<foo>>()
{
spamSpamAndSpam,
spamSpamSpamSausageEggsAndSpam,
//etc.
};
IEnumerable<foo> items = lists.SelectMany(item => item);
//do stuff with items.
答案 1 :(得分:2)
我能想到的最好是:
var everything = spam1.Concat(spam2).Concat(spam3);
var itemsIWant = everything.Where(x => Brian.Contains(x));
答案 2 :(得分:1)
Union()会解决您的问题吗?
List<foo> spamSpamAndSpam;
List<foo> spamSpamSpamSausageEggsAndSpam;
List<foo> spamSpamSpamSausageEggsBaconAndSpam;
List<foo> spamSpamSpamSpamSpamWithoutSpam;
List<foo> spamSpamSpamSpamSpamSpamSpamSpamSpamLovelySpamWonderfulSpam;
var x = spamSpamAndSpam
.Union(spamSpamSpamSausageEggsAndSpam)
.Union(spamSpamSpamSausageEggsBaconAndSpam)
.Union(spamSpamSpamSausageEggsBaconAndSpam)
.Union(spamSpamSpamSpamSpamWithoutSpam)
.Union(spamSpamSpamSpamSpamSpamSpamSpamSpamLovelySpamWonderfulSpam)
.Where(x => ..... );
注意:正确记录,Union排除了返回集中的重复项。这是Concat方法的不同行为,它返回输入序列中的所有元素,包括重复。由于重复排除不是必需的,因此Concat可能更好