tags:

views:

123

answers:

5

Hi,

I'm creating a collection of one to one mappings from Foo to Baa.

Baa contains a collection of unique instances of Foo.

Here's some code that does the job:

Dictionary<Foo, Baa> mappings = new Dictionary<Foo, Baa>();

foreach (Baa baa in CollectionOfBaa)
{
    foreach (Foo foo in baa.CollectionOfFoo)
    {
        mappings.Add(foo, baa);
    }
}   

Is there a better way to do this using LINQ?

I'm not adverse to replacing the dictionary with a list of KeyValuePair.

Thanks.

+1  A: 
var keyValuePairs = from baa in CollectionOfBaa
                    from foo in baa.CollectionOfFoo
                    select new KeyValuePair(baa,foo);

foreach item in keyValuePairs
{
mappings.Add(item.key,item.Value);
}
Flo
+5  A: 

You could use

var mappings = (from baa in CollectionOfBaa
                from foo in  baa.CollectionOfFoo
                select new { foo, baa }).ToDictionary(e => e.foo, e=> e.baa);
Jens
Wow, awesome ineffectiveness. Doing 3 foreach loops, creating n temporary objects and invoking n*2-times an anonymous function.And it does not even add readability (IMHO).
Jaroslav Jandek
+2  A: 

Improve how? Performance? No. Readability? Not for me.

Well, maybe this for readability (I still prefer the foreach version though)?

CollectionOfBaa.ForEach(baa =>
    baa.ForEach(foo =>
        mappings.Add(foo, baa)));
Jaroslav Jandek
A: 

Summerising all the comments and answers we get:

Speed: Using LINQ is actually slower.

Readability: This is a subjective point, but I agree with all the comments stating that the original foreach loops are the most readable.

I'm going to stick with the original code.

Thanks for all the answers.

elggarc
A: 

Since KeyValuePairs are acceptable, consider an IEnumerable of them:

var mappings = from parent in CollectionOfBaa
               from child in parent.CollectionOfFoo
               select new KeyValuePair<Foo,Baa>(child, parent);
Handcraftsman