我有一个键值对列表列表,我想将其转换为标准格式并进一步将其导出为表格。为此,我需要获取列表中存在的所有唯一 key 。如何使用 LINQ 获取唯一键?
我的源数据具有这种形式:
var sourceData = new List<List<KeyValuePair<string, string>>>();
...
var uniqueKeyNames = sourceData.SomeLinqCodeHere....
非常感谢
最佳答案
听起来您只需要 SelectMany
、Select
和 Distinct
的组合:
var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP
.Select(kvp => kvp.Key) // Select just the keys
.Distinct();
请注意,如果您想多次遍历 allKeys
,您可能想要具体化查询,例如通过在末尾调用 ToList
:
var allKeys = sourceData.SelectMany(list => list) // Flatten to a sequence of KVP
.Select(kvp => kvp.Key) // Select just the keys
.Distinct()
.ToList();
关于c# - 在 LINQ 中选择 List of KeyValuePairs 中的所有键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18514098/