组合多个元素集合的优雅方式? [英] Elegant way to combine multiple collections of elements?

查看:22
本文介绍了组合多个元素集合的优雅方式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有任意数量的集合,每个集合都包含相同类型的对象(例如,List fooList bar).如果这些集合本身在一个集合中(例如,类型为 List>,我可以使用 SelectMany 将它们全部组合成一个集合.>

但是,如果这些集合不在同一个集合中,我的印象是我必须编写这样的方法:

public static IEnumerable;合并(参数ICollection[] toCombine){返回到Combine.SelectMany(x => x);}

然后我会这样称呼它:

var combine = Combine(foo, bar);

是否有一种干净、优雅的方式来组合(任意数量的)集合,而无需编写像上面的 Combine 这样的实用方法?看起来很简单,应该有一种方法可以在 LINQ 中做到这一点,但也许没有.

解决方案

我想您可能正在寻找 LINQ 的 .Concat()?

var combine = foo.Concat(bar).Concat(foobar).Concat(...);

或者,.Union() 将删除重复元素.

Say I have an arbitrary number of collections, each containing objects of the same type (for example, List<int> foo and List<int> bar). If these collections were themselves in a collection (e.g., of type List<List<int>>, I could use SelectMany to combine them all into one collection.

However, if these collections are not already in the same collection, it's my impression that I'd have to write a method like this:

public static IEnumerable<T> Combine<T>(params ICollection<T>[] toCombine)
{
   return toCombine.SelectMany(x => x);
}

Which I'd then call like this:

var combined = Combine(foo, bar);

Is there a clean, elegant way to combine (any number of) collections without having to write a utility method like Combine above? It seems simple enough that there should be a way to do it in LINQ, but perhaps not.

解决方案

I think you might be looking for LINQ's .Concat()?

var combined = foo.Concat(bar).Concat(foobar).Concat(...);

Alternatively, .Union() will remove duplicate elements.

这篇关于组合多个元素集合的优雅方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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