Linq将索引器作为IEnumerable。选择选择器

问题描述 投票:0回答:1

是否存在允许将索引器作为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[]);

索引器毕竟只是方法...

c# linq indexer
1个回答
1
投票

无法直接为索引器编写“方法组”,但是您可以在Dictionary<TKey, TValue>上编写扩展方法并使用该方法的方法组:

public static TValue Get<TKey, TValue>(this Dictionary<TKey, TValue> dict, TKey key) => dict[key];

现在您可以在lambda中使用someDict.Get

© www.soinside.com 2019 - 2024. All rights reserved.