【问题标题】:Linq overloading where clause to exclude a specific typeLinq 重载 where 子句以排除特定类型
【发布时间】:2012-10-01 15:23:29
【问题描述】:

我正在实现一个扩展方法,该方法返回 TKeyIDictionary<TKey, TValue> 作为参数。如果TValuedouble,则该方法可能会返回具有最高值的TKey。否则,它会随机返回一个TKey

    public static TKey Sample<TKey>(this IDictionary<TKey, double> probabilityTable, Random r)
    {
        probabilityTable.Normalize();

        var roll = r.NextDouble();
        var temp = 0.0;
        foreach (var key in probabilityTable.Keys)
        {
            temp += probabilityTable[key];
            if (roll <= temp)
                return key;
        }

        return default(TKey);
    }

    public static TKey Sample<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, Random r)
    {
        return dictionary.Skip(r.Next(dictionary.Count)).FirstOrDefault().Key;
    }

    public static IDictionary<TKey, double> Normalize<TKey>(this IDictionary<TKey, double> probabilityTable)
    {
        if (probabilityTable.Any(x => x.Value < 0))
            throw new ArgumentOutOfRangeException("probabilityTable", "Probability is expected to be positive.");

        var sum = probabilityTable.Sum(x => x.Value);

        if (Math.Abs(sum - 1) > 1e-8)
            return probabilityTable.ToDictionary(x => x.Key, x => x.Value / sum);

        if (Math.Abs(sum) < 1e-8)
            return probabilityTable.ToDictionary(x => x.Key, x => 1.0 / probabilityTable.Count);

        return probabilityTable;
    }

问题是Sample&lt;TKey, TValue&gt; 总是被调用,即使使用doubleTValue。我可以用 where 子句指定类型 TValue exclude double 的任何方式吗?即where TValue: !double

调用扩展函数的代码如下:

        var r = new Random();
        var pt = new Dictionary<char, double> {{'A', 0.1}, {'B', 0.2}, {'C', 0.7}};
        var ct = new Dictionary<char, char> {{'A', 'D'}, {'B','E'}, {'C', 'F'}};
        Console.WriteLine(pt.Sample(r)); // expected to return 'C' mostly but uniformly returns key
        Console.WriteLine(ct.Sample(r));

【问题讨论】:

  • 如果我运行此代码(取消对Normalize 的调用,此处未显示),我将得到doublechar 的预期分布。也许你的Normalize 方法坏了?
  • @Rawling 对不起,这只是分类分布的归一化方法。我加了。

标签: linq methods dictionary where


【解决方案1】:

约束不是签名的一部分,也许下面的链接可以帮助你:

http://blogs.msdn.com/b/ericlippert/archive/2009/12/10/constraints-are-not-part-of-the-signature.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-22
    • 2014-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多