2013-06-24 57 views
1

我有一個按鈕列表List<Button> buttons,每個按鈕都包含一個標記對象。通過字典中的標記獲取按鈕c#

然後Dictionary對象

Dictionary<int, string> buttonGroups = new Dictionary<int, string>(); 

如何返回按鈕的ListList<Button> buttons,他們的標籤符合使用LINQ在buttonGroups的鑰匙?

回答

5
buttons.Where(b => buttonGroups.ContainsKey((int)b.Tag)) 
1

試試這個

listButtons.Where (button => !string.IsNullOrEmpty(button.Tag) && buttonGroups.Containskey (int.Parse(button.Tag)).ToList() 
3
List<Button> matches = buttons.Where(b => buttonGroups.Keys.Any(k => k == b.Tag)).ToList(); 

或用連接(這可能是稍快):

List<Button> matches =  
    (from b in buttons 
    join g in buttonGroups.Keys 
     on b.Tag == g 
    select b) 
    .ToList();