[英]Remap Lookup keys in C# using LINQ
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: 我想要做的是通过以下方式将查找中的字符串键重新映射到KeyModel
实体:
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<,>
. 因此,您首先使用SelectMany
重新线性化ILookup<,>
,然后重新创建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()
显然,您需要KeyModel
来定义GetHashCode()
和Equals()
,或者需要IEqualityComparer<KeyModel>
作为ToLookup()
的参数传递
You can use a simple foreach
-loop. 您可以使用简单的foreach
-loop。
First you need to transform your Lookup into a Dictionary. 首先,您需要将Lookup转换为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. 不是最快的解决方案,也许有人想出了一个不错的LINQ。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.