选择许多字典问题
本文关键字:问题 字典 许多 选择 | 更新日期: 2023-09-27 17:51:15
我正在努力使用Linq
语句从项目列表中获取项目列表并转换为字典。
我有一个"Windows"列表,其中有一个"控件"列表,但一个控件类型也有一个控件列表,我似乎无法弄清楚(就在我以为我理解Linq的时候:))
当前工作的嵌套foreach循环
public static Dictionary<int, Dictionary<int, bool>> _windowControlVisibilityMap = new Dictionary<int, Dictionary<int, bool>>();
public static void RegisterControlVisibility(IEnumerable<GUIWindow> windows)
{
_windowControlVisibilityMap.Clear();
foreach (var window in windows)
{
var controlMap = new Dictionary<int, bool>();
foreach (var control in window.Controls)
{
if (control is GUIGroup)
{
foreach (var grpControl in (control as GUIGroup).Controls)
{
controlMap.Add(grpControl.ControlId, grpControl.IsWindowOpenVisible);
}
}
controlMap.Add(control.ControlId, control.IsWindowOpenVisible);
}
_windowControlVisibilityMap.Add(window.WindowId, controlMap);
}
}
我在Linq查询中做同样的荒谬尝试。(不工作)
public static Dictionary<int, Dictionary<int, bool>> _windowControlVisibilityMap = new Dictionary<int, Dictionary<int, bool>>();
public static void RegisterControlVisibility2(IEnumerable<GUIWindow> windows)
{
_windowControlVisibilityMap.Clear();
foreach (var window in windows)
{
var dictionary = window.Controls.Select(k => new KeyValuePair<int, bool>(k.ControlId, k.IsWindowOpenVisible))
.Concat(window.Controls.OfType<GUIGroup>().SelectMany(grp => grp.Controls)
.Select(k => new KeyValuePair<int, bool>(k.ControlId, k.IsWindowOpenVisible)));
// _windowControlVisibilityMap.Add(window.WindowId, dictionary);
}
}
如果有人能给我指出正确的方向,让这个Linq语句工作,那就太棒了:)
这里有一些模拟对象来帮助你帮助我,LOL
public class GUIWindow
{
public int WindowId { get; set; }
public List<GUIControl> Controls { get; set; }
}
public class GUIControl
{
public int ControlId { get; set; }
public bool IsWindowOpenVisible { get; set; }
}
public class GUIGroup : GUIControl
{
public List<GUIControl> Controls { get; set; }
}
谢谢
下面应该可以工作:
window.Controls.Select(x => new { x.ControlId, x.IsWindowOpenVisible })
.Concat(window.Controls
.OfType<GUIGroup>()
.SelectMany(x => x.Controls)
.Select(x => new { x.ControlId, x.IsWindowOpenVisible }))
.ToDictionary(x => x.ControlId, x => x.IsWindowOpenVisible);
但是哈姆雷特有一个有效的观点:GUIGroup
中的每个控件都可以是另一个GUIGroup
。你需要递归来解决这个问题:
Func<IEnumerable<GUIControl>, IEnumerable<Tuple<int, bool>> getValues = null;
getValues = x => x.Select(x => Tuple.Create(x.ControlId, x.IsWindowOpenVisible))
.Concat(getValues(window.Controls
.OfType<GUIGroup>()
.SelectMany(x => x.Controls)));
getValues(window.Controls).ToDictionary(x => x.Item1, x => x.Item2);