如何使不带参数的 SelectMany 适用于通用 IEnumerable<T>

How to make SelectMany without argument work for generic IEnumerable<T>

我正在尝试创建一个 SelectMany() 扩展,它可以在没有任何查询选择器的情况下工作(所以根本没有参数)。我想出了以下内容:

public static IEnumerable<V> SelectMany<T, V>(this IEnumerable<T> enumerable) where T : IEnumerable<V> {
    return enumerable.SelectMany(e => e);
}

但是当我尝试这样调用它时,无法识别类型参数:

var d = new Dictionary<string, List<decimal>>();
var values = d.Values.SelectMany();

The type arguments for method 'CollectionsExtensions.SelectMany(IEmumerable' cannot be inferred from the usage. Try specifying the type arguments explicitly.

它只适用于:

public static IEnumerable<V> SelectMany<K, V>(this Dictionary<K, List<V>>.ValueCollection enumerable) {
    return enumerable.SelectMany(e => e);
}

我错过了什么?

LINQ 的 SelectMany 方法需要一个从 任意 对象提供 IEnumerable<V> 的选择器函数。

您希望 SelectMany 方法改为处理 IEnumerable<IEnumerable<V>> 对象,因此无需指定选择器函数。

所以保持简单:

static IEnumerable<T> SelectMany<T>(this IEnumerable<IEnumerable<T>> enumerable)
    => enumerable.SelectMany(e => e);