我正在努力使用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 语句正常工作,那就太棒了:)
这是一些可以帮助您帮助我的模拟对象,大声笑
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; }
}
谢谢