我有一个Person对象,我想将它转换为ConcurrentDictionary.有一种将Array转换为Dictionary的扩展方法.有没有将Array转换为ConcurrentDictionary的扩展方法?
public class Person { public Person(string name,int age) { Name =name; Age = age; } public string Name { get; set; } public int Age { get; set; } } Dictionary<int,Person> PersonDictionary = new Dictionary<int,Person>(); Person[] PersonArray = new Person[] { new Person("AAA",30),new Person("BBB",25),new Person("CCC",2),new Person("DDD",1) }; PersonDictionary = PersonArray.ToDictionary(person => person.Age);
用于将Array转换为ConcurrentDictionary的任何类似的扩展方法/ lambda表达式?
解决方法
当然,使用接受IEnumerable< KeyValuePair< int,Person>>的构造函数:
var personDictionary = new ConcurrentDictionary<int,Person> (PersonArray.ToDictionary(person => person.Age));
var将类型推断为ConcurrentDictionary< int,Person>.
如果您要创建一个扩展方法,正如Wasp建议的那样,我建议使用以下版本,它提供了一些更流畅的语法:
public static ConcurrentDictionary<TKey,TValue> ToConcurrentDictionary<TKey,TValue> (this IEnumerable<TValue> source,Func<TValue,TKey> valueSelector) { return new ConcurrentDictionary<TKey,TValue> (source.ToDictionary(valueSelector)); }
用法类似于ToDictionary,创建一致的感觉:
var dict = PersonArray.ToConcurrentDictionary(person => person.Age);