c# - 泛型方法的可为空参数类型 <T>?

标签 c# types pivot generics

我正在使用以下位置提供的枢轴方法: 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/

相关文章:

c# - 消除 ASP.NET 网站和 ASP.NET WebAPI 的跨域/子域 OPTIONS 请求

c# - 我将如何同步运行异步 Task<T> 方法?

sql - 帮助 PIVOT

c# - ASP.NET MVC : Get user id of currently logged in user

c# - 如何使用 C# 代码实现 100% cpu 负载

Ruby:获取查询字符串中值的正确类型

C#:数据类型与类型相同吗?

python - 结合python中的几种结构类型

python - 棘手的 MySQL 查询而不是 Python 脚本来实现结果?

sql - 使用 unpivot 时如何解决列类型的差异?