How do you convert a dictionary to a ConcurrentDictionary?

后端 未结 4 1049
眼角桃花
眼角桃花 2021-01-17 12:04

I have seen how to convert a ConcurrentDictionary to a Dictionary, but I have a dictionary and would like to convert to a ConcurrentDictionary. How do I do that?... better

4条回答
  •  -上瘾入骨i
    2021-01-17 12:24

    A LINQ-To-Objects statement is ultimately an IEnumerable so you can pass it to the ConcurrentDictionary constructor, eg:

    var customers = myCustomers.Select(x => new KeyValuePair(x.id, x));
    var dictionary=new ConcurrentDictionary(customers);
    

    This may not work with other providers. Linq to Entities for example, converts the entire LINQ statement to SQL and can't projection to a KeyValuePair. In this case you may have to call AsEnumerable() or any other method that forces the IQueryable to execute, eg:

    var customers = _customerRepo.Customers.Where(...)
                                 .AsEnumerable()
                                 .Select(x => new KeyValuePair(x.id, x));
    var dictionary=new ConcurrentDictionary(customers);
    

    Select() with no arguments is not an IEnumerable or IQueryable method so I suppose it's a method provided by some other ORM. If Select() returns an IEnumerable you can use the first option, otherwise you can use AsEnumerable()

提交回复
热议问题