MyDict=new Dictionary>(); 其中包含 -6ren">
gpt4 book ai didi

C# : Merging Dictionary and List

转载 作者:太空宇宙 更新时间:2023-11-03 20:39:14 25 4
gpt4 key购买 nike

我有一个 ListString 就像

List<String> MyList=new List<String>{"A","B"};

和一个

Dictionary<String, Dictionary<String,String>> MyDict=new Dictionary<String,Dictionary<String,String>>(); 

其中包含

 Key      Value
Key Value

"ONE" "A_1" "1"
"A_2" "2"
"X_1" "3"
"X_2" "4"
"B_1" "5"

"TWO" "Y_1" "1"
"B_9" "2"
"A_4" "3"
"B_2" "6"
"X_3" "7"

我需要将列表和字典合并成一个新的字典

 Dictionary<String,String> ResultDict = new Dictionary<String,String>()

生成的字典包含

Key Value

"A_1" "1"
"A_2" "2"
"B_1" "5"
"A_4" "3"
"B_2" "6"
"X_2" "4"
"X_3" "7"

合并规则

  1. 首先添加子字符串等于列表中任何项目的项目。
  2. 然后合并“MyDict”中的项目,这样结果就不会包含重复的键和重复的值。

这是我的源代码。

        Dictionary<String, String> ResultDict = new Dictionary<string, string>();
List<String> TempList = new List<string>(MyDict.Keys);
for (int i = 0; i < TempList.Count; i++)
{
ResultDict = ResultDict.Concat(MyDict[TempList[i]])
.Where(TEMP => MyList.Contains(TEMP.Key.Contains('_') == true ? TEMP.Key.Substring(0, TEMP.Key.LastIndexOf('_'))
: TEMP.Key.Trim()))
.ToLookup(TEMP => TEMP.Key, TEMP => TEMP.Value)
.ToDictionary(TEMP => TEMP.Key, TEMP => TEMP.First())
.GroupBy(pair => pair.Value)
.Select(group => group.First())
.ToDictionary(pair => pair.Key, pair => pair.Value); }
for (int i = 0; i < TempList.Count; i++)
{
ResultDict = ResultDict.Concat(MyDict[TempList[i]])
.ToLookup(TEMP => TEMP.Key, TEMP => TEMP.Value)
.ToDictionary(TEMP => TEMP.Key, TEMP => TEMP.First())
.GroupBy(pair => pair.Value)
.Select(group => group.First())
.ToDictionary(pair => pair.Key, pair => pair.Value);
}

它工作正常,但我需要消除两个或至少一个 for 循环(使用 LINQ 或 LAMBDA 表达式执行此操作的任何方式)

最佳答案

这是您可以根据要求使用 LINQ 和 lambda 执行此操作的一种方法:

var keysFromList = new HashSet<string>(MyList);
var results =
MyDict.Values
.SelectMany(x => x)
.OrderBy(x => {
int i = x.Key.LastIndexOf('_');
string k = (i < 0) ? x.Key.Trim()
: x.Key.Substring(0, i);
return keysFromList.Contains(k) ? 0 : 1;
})
.Aggregate(new {
Results = new Dictionary<string, string>(),
Values = new HashSet<string>()
},
(a, x) => {
if (!a.Results.ContainsKey(x.Key)
&& !a.Values.Contains(x.Value))
{
a.Results.Add(x.Key, x.Value);
a.Values.Add(x.Value);
}
return a;
},
a => a.Results);

关于C# : Merging Dictionary and List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3748998/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com