Nullable parameter type <T> for a generic method?
I'm using the pivot method presented at: http://www.extensionmethod.net/Details.aspx?ID=147
My question is: How can i use a nullable type as the second generic key?
public static Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSou开发者_运维问答rce> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, TSecondKey> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate) {
var retVal = new Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>>();
var l = source.ToLookup(firstKeySelector);
//l.Dump("Lookup first key");
foreach (var item in l) {
var dict = new Dictionary<TSecondKey, TValue>();
retVal.Add(item.Key, dict);
var subdict = item.ToLookup(secondKeySelector);
foreach (var subitem in subdict) {
dict.Add(subitem.Key, aggregate(subitem));
}
}
return retVal;
}
You should be able to use a nullable type just normally as long as the values aren't null - but you can't use null
(or an empty Nullable<T>
) as a key - it simply can't work.
It would make more sense to ensure (in the calling code) that secondKeySelector
always returns something non-null; in the case of Nullable<T>
perhaps by calling x => x.Foo.Value
(if you see what I mean).
Another approach would be to declaratively preclude Nullable<T>
here, by adding where TSecondKey : struct
- but since string
is a common key (and is a reference-type) this may be an undesirable approach.
You can be explicit on the use of the Nullable<T>
on your generic declaration, which will limit you to use a Nullable
on your method.
public static Dictionar<TFirstKey, Dictionary<Nullable<TSecondKey>, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> source, Func<TSource, TFirstKey> firstKeySelector, Func<TSource, Nullable<TSecondKey>> secondKeySelector, Func<IEnumerable<TSource>, TValue> aggregate)
where TSecondKey : struct
{}
As your using a Nullable<T>
, you have to repeat the constraint for T
to your implementation.
Please also note that Dictionary
might not be happy with null key.
精彩评论