【问题标题】:How to replace Linq Cast expression?如何替换 Linq Cast 表达式?
【发布时间】:2010-10-26 11:17:54
【问题描述】:

问题:我有一些用于 pgp 加密的代码: http://blogs.microsoft.co.il/blogs/kim/archive/2009/01/23/pgp-zip-encrypted-files-with-c.aspx

它有以下方法,使用一些 LINQ。 我仍在使用 .NET 2.0,无法切换到更高版本,但...

如何用普通代码替换这个表达式? 我不太了解 Linq,我猜它做了一些排序?

 private PgpSecretKey GetFirstSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
        {
            foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
            {
                PgpSecretKey key = kRing.GetSecretKeys()
                    .Cast<PgpSecretKey>()
                    .Where(k => k.IsSigningKey)
                    .FirstOrDefault();
                if (key != null)
                    return key;
            }
            return null;
        }

【问题讨论】:

    标签: c# .net linq pgp openpgp


    【解决方案1】:

    类似:

    foreach (PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings())
    {
        foreach (PgpSecretKey key in kRing.GetSecretKeys())
        {
            if (key.IsSigningKey)
            {
                return key;
            }
        }
    }
    return null;
    

    foreach 隐式执行到目标类型的转换。诚然,最初的 LINQ 会更令人愉快地写成:

    return (from keyring in secretKeyRingBundle.GetKeyRings()
            from PgpSecretKey key in keyring.GetSecretKeys()
            where key.IsSigningKey)
           .FirstOrDefault(); 
    

    (您可能也需要将第一个from 子句设置为强类型;这取决于GetKeyRings() 声明返回的内容。)

    【讨论】:

    • 作为旁注,你省略了 if (key != null),但它需要在 "if (key.IsSigningKey)" 之前检查,所以它看起来像 2 个错误,一个在你的,原始代码中的另一个。而且由于您写了“类似的东西”,因此它在原始版本中被视为一个错误。
    • @Quandary:那么GetSecretKeys() 可以返回空值吗?这看起来很奇怪。 FirstOrDefault 的结果显然可能为 null,但这是另一回事。
    • 可能,如果 KeyRingBundle 输入文件的内容不正确。
    • @Quandary:在这种情况下为什么不抛出异常?目前尚不清楚您是否推测它可能,或者您是否知道是这种情况。
    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多