views:

43

answers:

1

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;
        }
+5  A: 

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.)

Jon Skeet