【发布时间】:2018-07-20 08:47:17
【问题描述】:
我有两个字典,都是Dictionary<string, List<List<string>> 类型。
我想从字典 1 中选择与字典 2 中的值/条目匹配的条目范围。
例如字典 1 具有键 01, 01.1,字典 2 具有匹配值 01, 01.1. 在键 1
首先,我在键 1 处从字典 2 中获取条目,如下所示:
var dictList = (from entry in DbDict
where entry.Key == id.ToString() // id = 1
select entry).ToList();
我尝试通过 linq 选择这些,如下所示:
var matchingEntries = (from entry in ExcelDict
where ExcelDict.Keys.Equals(dictList[0].Value)
select entry).ToList();
并沿着这些思路进行了更多尝试,但它不会返回任何结果。
如何从字典 1 中获取值对的范围,其键与字典 2 的值匹配?
编辑1:
Dictionary 1:
Key Value
01 "these", "are"
..., ...
01.1 "just", "some"
..., ...
02 "sample", "values"
..., ...
Dictionary 2:
Key Value
1 "01", "01.1"
"foo", "bar"
..., ...
2 "02", "02.21"
"value1" "value2"
编辑2:
预期输出:
"01", "01.1"
"foo", "bar"
编辑3:
在 cmets 中请求的可编译输入。这正是我正在处理的结构:
var dict1 = new Dictionary<string, List<List<string>>>();
dict1.Add("01", new List<List<string>> { new List<string> { "these" }, new List<string> { "are" } });
dict1.Add("01.1", new List<List<string>> { new List<string> { "just" }, new List<string> { "some" } });
dict1.Add("02", new List<List<string>> { new List<string> { "sample" }, new List<string> { "values" } });
var dict2 = new Dictionary<string, List<List<string>>>();
dict2.Add("1", new List<List<string>> { new List<string> { "01", "01.1" }, new List<string> { "foo", "bar" } });
dict2.Add("2", new List<List<string>> { new List<string> { "02", "value1" }, new List<string> { "02.21", "value2" } });
编辑4:
抱歉回复晚了。 Gaurang Dave 在 cmets 中的建议和接受的答案都对我有用。感谢大家的帮助!
【问题讨论】:
-
为什么 dict1 中的键
02的条目没有显示在结果中?该键与dict2中的键2的值匹配!? -
老实说:我宁愿为您的结构构建专门的类并实现所需的功能和属性。这通常比摆弄嵌套的字典和列表更快、更容易处理。
-
@arekzyla:在 OP 中添加。
-
使用 FooBar 示例绝不是一个好主意,因为它们可能意味着任何东西。我还不清楚你想要什么。我的意思是,从您的示例来看,它应该做的只是返回 Dict2 中 key=1 的值吗?
-
@Allix 试试这个。它适用于您在 OP 中提到的值。您可以使用您可能遇到的其他情况来检查这一点。让我知道它是否有效
string selectedId = Convert.ToString(1); var result = dict2 .Where(d2 => d2.Key == selectedId) .Where(d2 => d2.Value.Any(d2lst => d2lst.Any(d2lst1 => dict1.Keys.Contains(d2lst1)))) .Select(d2 => d2.Value) .ToList();
标签: c# linq dictionary