简体   繁体   English

相当于Javas Guavas Maps.uniqueIndex的C#

[英]C# equivalent of Javas Guavas Maps.uniqueIndex

Guava has a static method 番石榴有静态方法

Maps.uniqueIndex(Iterable<V> values, Function<? super V,K> keyFunction) 

which maps each entry in the entered collection by the result of the entered function applied on respective elements. 它通过应用在各个元素上的输入函数的结果来映射输入集合中的每个条目。

Is there any analogues for C# that do the same? C#是否有类似的功能?

Java sample Java样本

Map<String, Human> idToHuman = Maps.uniqueIndex(humans, Human::getPassportId) ; Map<String, Human> idToHuman = Maps.uniqueIndex(humans, Human::getPassportId) ;

In case of C# where we have IEnumerable<V> instead of Iterable<V> and Dictionary insetead of Map . C# ,我们有IEnumerable<V>而不是Iterable<V>并且Map Dictionary insetead是。 That's why we can put in C# 这就是为什么我们可以放入C#

using System.Linq;

...

Dictionary<K, V> result = values.ToDictionary(v => keyFunction(v));

where values impelements IEnumerable<V> and keyFunction is Func<V, K> . 其中values促进IEnumerable<V>keyFunctionFunc<V, K> In your case C# code can be something like this 在您的情况下,C#代码可以是这样的

using System.Linq;

... 

// I've turned Java getPassportId method into PassportId property 
// "Dictionary<String, Human>" declaration can be changed into just "var" 
Dictionary<String, Human> idToHuman = humans.ToDictionary(human => human.PassportId);    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM