I have my Lookup looking like this:
Lookup<string, DataModel> lookup;
Besides that I have dictionary containing key mappings:
Dictionary<string, KeyModel> keyMappings;
What I want to do is to re-map string keys in lookup to the KeyModel
entities in the following way:
Lookup <string, DataModel> lookup;
||
||
Dictionary<string, KeyModel> keyMappings;
___________|
v
Lookup<KeyModel, DataModel> result;
Given:
Dictionary<string, KeyModel> keyMappings = ...;
ILookup<string, DataModel> lookup = ...;
the response is:
ILookup<KeyModel, DataModel> lookup2 = lookup
.SelectMany(x => x, (grouping, element) => new { Key = keyMappings[grouping.Key], Element = element })
.ToLookup(x => x.Key, x => x.Element);
So you first re-linearize the ILookup<,>
by using SelectMany
, and then recreate the ILookup<,>
.
Clearly you need your KeyModel
to define the GetHashCode()
and the Equals()
, or you need an IEqualityComparer<KeyModel>
to pass as the parameter of the ToLookup()
You can use a simple foreach
-loop.
First you need to transform your Lookup into a Dictionary. See here .
foreach (KeyValuePair<string, DataModel> kvp in lookup) {
KeyModel outValue;
if (keyMappings.TryGetValue(kvp.Key, out outValue))
{
result.Add(outValue, lookup[kvp.Key]);
}}
Not the fastest solution, maybe someone is coming up with a nice LINQ.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.