Access dictionary value inside linq method

I got the following structures:

public class Foo 
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
}

var fooMapping = GetFooMapping();
var fooObjects = GetFoos();

fooObjects.All(foo =>
{
    Tuple<string, string> value = null;
    if (fooMapping.TryGetValue(foo.Code, out value))
    {
        foo.Description = value.Item1;
        foo.Name = value.Item2;
    };
    return true;
});

The GetFoos method returns an Enumerable of Foo objects that don't have all their properties set.

GetFooMapping returns an

IDictionary<string, Tuple<string, string>> 

where TKey = Foo.Code and TValue.Item1 = Foo.Description and TValue.Item2 = Foo.Name.

While debugging, after running through the last lines of code I see that some of the properties weren't set even though the Foo.Code exists in the dictionary. Am I missing something?

Upvotes: 0

Views: 182

Answers (1)

juharr
juharr

Reputation: 32266

Instead of All you could use Select and assign the result back to fooObjects

fooObjects = fooObjects.Select(foo =>
    {
        Tuple<string, string> value = null;
        if (fooMapping.TryGetValue(foo.Code, out value))
        {
            foo.Description = value.Item1;
            foo.Name = value.Item2;
        }
        return foo;
    });

The main issue that you are likely having is that All is iterating over an IEnumerable that is generating it's items. Then the next time you iterate fooObjects it generates them again and the changes in All are lost. Further this is not how Linq is meant to be used. All is meant for checking a predicate over the collection, not for modifying or projecting.

The other option is to make sure you are working with a list and just use a foreach

var fooObjects = GetFoos().ToList();

foreach(var foo in fooObjects)
{
    Tuple<string, string> value = null;
    if (fooMapping.TryGetValue(foo.Code, out value))
    {
        foo.Description = value.Item1;
        foo.Name = value.Item2;
    }
}

Upvotes: 1

Related Questions