2011-11-22 56 views
2

我有一個List<Dictionary<String, String>> dictionaries。每個詞典將包含以下鍵 - WAP,SystemCodeSubSystemCode。 A System屬於WAP,並且Subsystem屬於System。您可能會看到數據的例子是這樣的:使用linq/lambdas獲取不同列表的最快方法

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

所以要:爲WAP /系統的每個組合,給我各子系統?你想把WAP /系統作爲結果的一部分嗎? –

+0

是的,這將是有益的,因爲我需要這些值進行搜索。 – link664

+1

匿名類型自動實現'Equals()'和'GetHashCode()',所以如果你使用'GroupBy(d => new {WAP = d [「WAP」],SystemCode = d [「SystemCode」]})'最後一個應該類似於第二個。 – millimoose

回答

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

這實際上是第二步的解決方案,而不是第三步,因爲如果只將第一個拉出組,那麼選擇意味着將第一個拉出組,因此會丟失具有不同子系統的所有組件。但是你讓我找到了最終的解決方案 - 「字典」。GroupBy(d => new {WAP = d [「WAP」],System = d [「SystemCode」],Subsystem = d [「SubSystemCode」]})。選擇(g => g.FirstOrDefault())'toush' – link664

+0

touche 。很高興我可以幫助 –

0

我嘗試以下LINQ查詢在LINQPad最終的結果應該包含所有三個問題的答案。

看看這是你想要的。我使用了嵌套的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如下圖所示:

enter image description here

相關問題