是否存在允许将索引器作为Select(Func<T,TResult> selector)
选择器传递的语法?例如,是否存在使用索引器执行以下代码的简写形式(即,不带“箭头”):
// full version using indexer
collection.Select(key => dictionary[key]);
以与其他成员函数相同的方式?例如:
// full
collection.Select(key => dictionary.ContainsKey(key));
// shorthand
collection.Select(dictionary.ContainsKey);
以下各项似乎都不起作用:
// shorthand attempts with invalid syntax
collection.Select(dictionary.[]);
collection.Select(dictionary[]);
索引器毕竟只是方法...
无法直接为索引器编写“方法组”,但是您可以在Dictionary<TKey, TValue>
上编写扩展方法并使用该方法的方法组:
public static TValue Get<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key) => dict[key];
现在您可以在lambda中使用someDict.Get
。