从字典值到 IEnumerable 的 Concat 列表

Mec*_*ius 2 .net c# linq dictionary

我有一个Dictionary<int, list<T>>并且想要得到一个IEnumerable<T>,它允许我遍历字典中所有列表的所有元素。这当然应该避免处理所有元素和其他性能成本高的操作。

我对 Linq 的处理方式不太正确:

IEnumerable<T> enumerable = dict.SelectMany(list).Foreach(list.ConcatAll()).ToEnum();
Run Code Online (Sandbox Code Playgroud)

如果Linq不是最佳方式,请提出其他选择。

Pav*_*ski 6

尝试使用以下代码

var enumerable = dict.Values.SelectMany(v => v);
Run Code Online (Sandbox Code Playgroud)

您正在访问Values字典集合,然后使用SelectMany方法将每个值投影为List<T>并展平为结果枚举

您的代码不起作用,因为SelectMany()接受Func作为集合选择器,也不需要使用Foreach方法。ToEnum()方法用法在这里也无效,它属于Enum类型并且几乎所有System.Linq方法都已经接受或返回IEnumerable<T>