[英]How to convert IDictionary<TKey, List<TValue> > to IDictionary<TKey, IEnumerable<TValue> >?
I have a function that return a IDictionary<TKey, List<TValue> >
. 我有一个返回IDictionary<TKey, List<TValue> >
的函数。
I have another function that takes a IDictionary<TKey, IEnumerable<TValue> >
. 我还有另一个函数,该函数采用IDictionary<TKey, IEnumerable<TValue> >
。
I need to pass the return of the first function to the second function. 我需要将第一个函数的返回值传递给第二个函数。
The compiler doesn't want to implicitlty convert the first into the second. 编译器不想将第一个转换为第二个。 So how could I convert the first into the second in O(1)? 那么如何将O(1)中的第一个转换为第二个呢?
I could always write a conversion function 我总是可以写一个转换函数
public static IDictionary<TKey, IEnumerable<TValue>> ToIEnumerable<TKey, TValue>(this IDictionary<TKey, List<TValue>> source)
{
return source.ToDictionary(s => s.Key, s => s.Value.AsEnumerable());
}
But I'm pretty sure this is not O(1), more like O(log n). 但是我很确定这不是O(1),更像O(log n)。
A related question here : Nested Interfaces: Cast IDictionary< TKey, IList< TValue > > to IDictionary< TKey, IEnumerable < TValue> >? 这里有一个相关的问题: 嵌套接口:将IDictionary <TKey,IList <TValue>>转换为IDictionary <TKey,IEnumerable <TValue>>?
Consider your second function, the one that 考虑你的第二个功能,那个
takes a IDictionary<TKey, IEnumerable<TValue> >
Now, if you give me a IDictionary<TKey, IEnumerable<TValue>>
, one of the things I should be able to do is set the value of one of the keys to a new TValue[]
, right? 现在,如果您给我一个IDictionary<TKey, IEnumerable<TValue>>
,我应该做的一件事情就是将其中一个键的值设置为一个new TValue[]
,对吗? After all, a TValue[]
is an IEnumerable<TValue>
, so it meets the constraint. 毕竟, TValue[]
是IEnumerable<TValue>
,因此它满足约束。
However, if somehow what you'd given me was (underneath the interface) a IDictionary<TKey, List<TValue>>
, I definitely shouldn't be allowed to set the value of a key to a TValue[]
, since a TValue[]
is not a List<TValue>
! 但是,如果您以某种方式给我的东西是(在接口下) IDictionary<TKey, List<TValue>>
,则绝对不应该将键的值设置为TValue[]
,因为TValue[]
不是List<TValue>
!
This is exactly the problem in the question you have linked, of course. 当然,这正是您所链接的问题中的问题。
Now, if you are happy to only ever read the parameter I pass you, you have a potential solution in moving from dictionaries to ILookup<TKey, TValue>
, which is a bit like a read-only dictionary from a key to a list of values. 现在,如果您很高兴只读取我传递给您的参数,那么您可以找到从字典到ILookup<TKey, TValue>
的潜在解决方案,这有点像从键到列表的只读字典。值。 If your methods respectively return and accept an ILookup<TKey, TValue>
there's of course no problem. 如果您的方法分别返回并接受ILookup<TKey, TValue>
那么当然没有问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.