我正在使用以下位置提供的枢轴方法: http://www.extensionmethod.net/Details.aspx?ID=147
我的问题是:如何使用可为空类型作为第二个通用键?
public static Dictionary<TFirstKey, Dictionary<TSecondKey, TValue>> Pivot<TSource, TFirstKey, TSecondKey, TValue>(this IEnumerable<TSource> 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;
}
最佳答案
只要值不为空,您就应该能够正常使用可空类型 - 但您不能使用 null
(或空 Nullable<T>
)作为键 - 它根本无法工作。
确保(在调用代码中)secondKeySelector
更有意义。总是返回非空值;在 Nullable<T>
的情况下也许通过调用 x => x.Foo.Value
(如果你明白我的意思)。
另一种方法是声明性地排除 Nullable<T>
在这里,添加 where TSecondKey : struct
- 但自从 string
是一个公共(public) key (并且是一个引用类型),这可能是一种不可取的方法。
关于c# - 泛型方法的可为空参数类型 <T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4656074/