我有List<Dictionary<String, String>> dictionaries
。每个字典都包含以下键:WAP
,SystemCode
和SubSystemCode
。 System
属于WAP
,而Subsystem
属于System
。您可能会看到的数据示例如下:
WAP | System | Subsystem
-------------------------
01 | 01 | 01
01 | 02 | 02
02 | 01 | 01
02 | 01 | 02
02 | 03 | 02
03 | 02 | 01
我基本上想要得到以下内容:
所有WAP代码的明确列表。
我认为var waps = dictionaries.Select(d => d["WAP"]).Distinct();
应该适用于此。
每个WAP代码的所有系统代码的明确列表。
以下内容应该有效:
var dictionaryGroups = dictionaries.GroupBy(d => d["WAP"]);
foreach (var dictionaryGroup in dictionaryGroups )
{
var wapNo = dictionaryGroup.Key;
var systemCodes = dictionaryGroup.Select(d => d["SystemCode"]).Distinct();
...
}
每个WAP代码的每个系统代码的所有子系统代码的清单。
不确定这个。
有人可以帮我解决最后一个问题吗?如果有更好的方法来做前两个,请随时告诉我。
答案 0 :(得分:3)
// linq expression
var dist = from d in dictionaries
group d by new { WAP = d["WAP"], System = d["System"] } into g
select g.FirstOrDefault();
//lambdas
var dist = dictionaries
.GroupBy(d => new { WAP = d["WAP"], System = d["System"] })
.Select(g => g.FirstOrDefault())
答案 1 :(得分:0)
我在LINQPad中尝试了以下linq查询,最终结果应包含所有三个问题的答案。
看看这是否是你想要的。我使用嵌套的GroupBy Linq运算符。
为了简化示例查询,我只使用了一个平面数组来表示上面显示的数据。您应该能够调整下面的示例查询以应用于实际的字典对象。
var dictionaries = new [] {
new { WAP = "1", System = "1", Subsystem = "1"},
new { WAP = "1", System = "2", Subsystem = "2"},
new { WAP = "2", System = "1", Subsystem = "1"},
new { WAP = "2", System = "1", Subsystem = "2"},
new { WAP = "2", System = "3", Subsystem = "2"},
new { WAP = "3", System = "2", Subsystem = "1"}
};
var query =
from d in dictionaries
group d by d.WAP into wapGroup
select new {
WAP = wapGroup.Key,
SystemGroup =
from s in wapGroup
group s by s.System into systemGroup
select new {
System = systemGroup.Key,
SubsystemGroup =
from s in systemGroup
group s by s.Subsystem into subsystemGroup
select new {
SubSystem = subsystemGroup.Key
}
}
};
query.Dump();
LINQPad的结果如下所示: