Richard
Richard

Reputation: 121

Search in dictionary of dictionaries

I have a dictionary defined as seen here:

Dictionary<int, Dictionary<string, object>> dict = new Dictionary<..>();

And a sample code for adding data:

dict.Add (X, new Dictionary<string, object> ());
dict [X].Add ("Car", CarObject);
dict [X].Add ("Seller", SellerObject);
dict [X].Add ("Key3", Z);

I want to search in the inner dictionary if it contains an object which then contains the following CarObject.Name = (wildcard)X1(wildcard) of the key "Car" but I just can't seem to get a grasp of how to get into the inner dictionary and then into the object with LINQ in order to search for the value.

Upvotes: 0

Views: 346

Answers (3)

Hamlet Hakobyan
Hamlet Hakobyan

Reputation: 33381

This will return all matching KeyValuePair<string, object>.

var query = dict.SelectMany(d => d.Value)
                .Where(i => i.Key == "Key1"
                    && (
                          i.Value is CarObject
                          ? ((CarObject)i.Value).Name.Contains("X1")
                          : false
                       ));

Upvotes: 1

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101681

You can try something like:

dict[X].Where(x => x.Value is CarObject && ((CarObject)x.Value).Name.Contains("X1"));

Or:

dict[X].Values.OfType<CarObject>().Any(x => x.Name.Contains("X1"))

Upvotes: 0

Cyral
Cyral

Reputation: 14153

Try the following:

var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1"));

If you want to get just the value and not the dictionary, and print the values, you can do this:

int X = 0, Z = 1;
dict[X].Add("Key1", CarObject);
dict[X].Add("Key2", SellerObject);
dict[X].Add("Key3", Z);

var results = dict[X].Where(x => (x.Value is CarObject) && ((CarObject)x.Value).Name.Contains("X1")).Select(x => x.Value);
foreach (var str in results)
   Console.WriteLine(str);

Upvotes: 0

Related Questions