Mariusz Ignatowicz
Mariusz Ignatowicz

Reputation: 1672

Use LINQ to match property values to Dictionary keys

Let's suppose I have these 2 simple classes:

public class MyObject
{
    public string name;
    public string objectProperty;
    [other properties]
}

public class Referencer
{
    public string name;
    public Dictionary<string, object> objectDictionary;
}

and a list of MyObject instances:

List<MyObject> myObjects = new List<MyObject>
{
    new MyObject(name: "name1", objectProperty: "objectProperty1", other properties...),
    new MyObject(name: "name2", objectProperty: "objectProperty2", other properties...),
    new MyObject(name: "name3", objectProperty: "objectProperty3", other properties...),
    other myObjects...
}

and such dictionary of dictionaries:

Dictionary<string, Dictionary<string, object>> sampleDictionary = new Dictionary<string, Dictionary<string, object>>
{
    {"name3", new Dictionary<string, object> { {"property1", "value1"}, {"property2", "value2"}  }  },
    {"name2", new Dictionary<string, object> { {"property3", "value3"}, {"property4", "value4"}  }  },
    {"name1", new Dictionary<string, object> { {"property5", "value5"}, {"property6", "value6"}  }  },
    other entries...
};

I need to be able to create a List<Referencer> matching myObjects to sampleDictionary according to the rule:

myObjects.name == sampleDictionary.Key

I've tried to use LINQ ForEach, Where, ToDictionary, but I think I have something missing here and need your help.

Upvotes: 2

Views: 750

Answers (1)

Sasha Alperovich
Sasha Alperovich

Reputation: 382

Augmenting the answer of @AleksAndreev a bit:

myObjects
    .Where(x => sampleDictionary.ContainsKey(x))
    .Select(x => new Referencer { name = x.name, objectDictionary = sampleDictionary[x.name] });

Upvotes: 2

Related Questions