【问题标题】:Get buttons by tag from a dictionary c#从字典c#中按标签获取按钮
【发布时间】:2013-06-24 14:21:03
【问题描述】:
我有一个按钮列表List<Button> buttons,每个都包含一个标签对象。
然后是一个字典对象
Dictionary<int, string> buttonGroups = new Dictionary<int, string>();
如何使用 LINQ 从 List<Button> buttons 返回按钮的 List,其中它们的标签与 buttonGroups 中的键匹配?
【问题讨论】:
标签:
c#
.net
linq
list
button
【解决方案1】:
buttons.Where(b => buttonGroups.ContainsKey((int)b.Tag))
【解决方案2】:
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();
【解决方案3】:
试试这个
listButtons.Where (button => !string.IsNullOrEmpty(button.Tag) && buttonGroups.Containskey (int.Parse(button.Tag)).ToList()