[C#.NET][LINQ] 查詢 Dictionary 集合中的物件索引值 并 找出上下一笔物件

原文:http://www.dotblogs.com.tw/yc421206/archive/2012/03/29/71131.aspx

我有SwitchFlag類別
public 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 集合這樣定義
private Dictionary<Control, SwitchFlag> _SwitchFlags = new Dictionary<Control, SwitchFlag>();
public Dictionary<Control, SwitchFlag> SwitchFlags
{
    get { return _SwitchFlags; }
    set { _SwitchFlags = value; }
}
查詢Dictionary 集合的索引,這樣寫
int findControlIndex(Control ctrl)
{
    int position = SwitchFlags
        .Select((item, index) => new { Ctrl = item.Key, Index = index })
        .Where(i => i.Ctrl.Name == ctrl.Name).First().Index
        ;
    
    return position;
}
依索引條件找出集合物件
Control moveControl(int position)
{
    var move = SwitchFlags
          .Select((item, index) => new { Ctrl = item.Key, Index = index })
          .Where(o => o.Index == (position)).First().Ctrl
          ;
    return move;
}
呼叫上述兩個方法
void Ctrl_KeyDown(object sender, KeyEventArgs e)
{
    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();
}
實作結果
image

若有謬誤,煩請告知,新手發帖請多包涵


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值