开发者

How to replace Linq Cast expression?

开发者 https://www.devze.com 2023-01-21 19:53 出处:网络
Question: I have some code for pgp encryption from here: http开发者_如何转开发://blogs.microsoft.co.il/blogs/kim/archive/2009/01/23/pgp-zip-encrypted-files-with-c.aspx

Question: I have some code for pgp encryption from here: http开发者_如何转开发://blogs.microsoft.co.il/blogs/kim/archive/2009/01/23/pgp-zip-encrypted-files-with-c.aspx

It has the below method, using some LINQ. I'm still on .NET 2.0 and can't switch higher, yet...

How can I replace this expression with ordinary code? I don't really understand Linq, I guess it does some sorting ?

 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;
        }


Something like:

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

foreach implicitly performs a cast to the target type. Admittedly the original LINQ would have been more pleasantly written as:

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

(You may need to make the first from clause strongly typed too; it depends on what GetKeyRings() is declared to return.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号