[C#.NET][LINQ] 查詢 Dictionary 集合中的物件索引值 並 找出上下一筆物件
我有SwitchFlag類別
class SwitchFlag
{
private bool _Enable = false;
public bool Enable
{
get { return _Enable; }
set { _Enable = value; }
}
private bool _IsTabStop=true;
public bool IsTabStop
{
get { return _IsTabStop; }
set { _IsTabStop = value; }
}
}
Dictionary 集合這樣定義
public Dictionary<Control, SwitchFlag> SwitchFlags
{
get { return _SwitchFlags; }
set { _SwitchFlags = value; }
}
查詢Dictionary 集合的索引,這樣寫
{
int position = SwitchFlags
.Select((item, index) => new { Ctrl = item.Key, Index = index })
.Where(i => i.Ctrl.Name == ctrl.Name).First().Index
;
return position;
}
依索引條件找出集合物件
{
var move = SwitchFlags
.Select((item, index) => new { Ctrl = item.Key, Index = index })
.Where(o => o.Index == (position)).First().Ctrl
;
return move;
}
呼叫上述兩個方法
{
Control current = (Control)sender;
if (!this.SwitchFlags.ContainsKey(current))
{
return;
}
int index = findControlIndex(current);//找出集合索引
int count = this.SwitchFlags.Count;
Control move = null;
if (this.NextKeys.Contains(e.KeyCode))
{
if (index == count - 1)
{
move = moveControl(0);
}
else
{
move = moveControl(index + 1);//找出下一個物件
}
}
else if (this.PreviousKeys.Contains(e.KeyCode))
{
if (index == 0)
{
move = moveControl(count - 1);
}
else
{
move = moveControl(index - 1);//找出上一個物件
}
}
move.Focus();
}
實作結果
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET