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;
        }
Stefan Steiger
  • 78,642
  • 66
  • 377
  • 442

1 Answers1

5

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • As a sidenote, you omitted if (key != null), but it needs to be checked before the "if (key.IsSigningKey)", so it looks like 2 bugs, one in yours, another in the original code. And since you wrote "something like", it qualifies as one bug, in the original. – Stefan Steiger May 26 '11 at 10:13
  • @Quandary: So can `GetSecretKeys()` return null values? That would seem odd. The result of `FirstOrDefault` could obviously be null, but that's a different matter. – Jon Skeet May 26 '11 at 10:34
  • It might, if the content of the KeyRingBundle input file is incorrect. – Stefan Steiger May 29 '11 at 06:47
  • @Quandary: Why wouldn't it just throw an exception in that case? It's not clear whether you're speculating that it might, or whether you know that's the case. – Jon Skeet May 29 '11 at 06:51