Reputation: 14906
I am trying to create a Lambda expressions that creates an object array from an IDictionary based on given named input.
This is what I have so far:
var dic = new Dictionary<string, object>()
{
{"some", "value"},
{"dateTime", DateTime.Now},
{"someNum", 52},
{"other", "values"}
};
string[] inputArray = { "input", "dateTime", "someNume" };
var processedArray = inputArray.Select(i => dic.Where(d => d.Key == i).Select(kvp => kvp.Value)).ToArray();
This doesn't work, it returns an IEnumerable<object>
but all the members are type KeyValuePair<string,object>
just, it appears, without the key data.
I think there are a few things wrong with this. I don't think I should be using dic.Select()
as key entries in dictionary are unique and I am obviously referencing the value wrong or missing a way to cast each result.
I am not sure how to achieve this using a single Lambda. I need to work out the Lambda as I plan to use it as a compiled Lambda.
Can someone advise me on how best to do this?
Upvotes: 0
Views: 156
Reputation: 13234
I think this should do the trick.
var processedArray =
(from key in inputArray
where dic.ContainsKey(key)
select dic[key]).ToArray();
Or using the fluent/dot syntax:
var processedArray = inputArray
.Where(key => dic.ContainsKey(key))
.Select(key => dic[key])
.ToArray();
If you want to still have an element in your processedArray
output in the case where the dictionary misses a key (e.g. for the "input" string in your example), you could do it like this for example (using null
for a missing entry in the dictionary):
var processedArray = inputArray
.Select(key => dic.ContainsKey(key) ? dic[key] : null)
.ToArray();
Upvotes: 3
Reputation:
You should be able to select these just by accessing the dictionary indices:
inputArray.Select(k => dic[k]);
Upvotes: 2