5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】早期リターンでネストを浅くする

Posted at

C#でメモ帳アプリのリストボックスをドラッグ&ドロップで順序変更できるように、
ListBox_Drop関数を作成した。
※別関数も必要だが、早期リターンでネストを浅くする が目的の記事のため割愛する。

ListBox_Drop
private void ListBox_Drop(object sender, DragEventArgs e)
{
    if (e.Data.GetDataPresent(typeof(Memo)))
    {
        var droppedData = e.Data.GetData(typeof(Memo)) as Memo;
        var target = ((FrameworkElement)e.OriginalSource).DataContext as Memo;

        if (droppedData != null && target != null)
        {
            int removedIdx = Memos.IndexOf(droppedData);
            int targetIdx = Memos.IndexOf(target);

            if (removedIdx != targetIdx)
            {
                Memos.RemoveAt(removedIdx);
                Memos.Insert(targetIdx, droppedData);

                for (int i = 0; i < Memos.Count; i++)
                {
                    _repo.UpdateOrder(Memos[i].Id, i);
                }
            }

        }
    }
}

ネストが深くて読みにくい。。
そこで、早期リターンを用いてネストを浅くした。

ListBox_Drop
private void ListBox_Drop(object sender, DragEventArgs e)
{
    if (!e.Data.GetDataPresent(typeof(Memo)))
        return;

    if (e.Data.GetData(typeof(Memo)) is not Memo droppedData)
        return;

    if (((FrameworkElement)e.OriginalSource).DataContext is not Memo target)
        return;

    int removedIdx = Memos.IndexOf(droppedData);
    int targetIdx = Memos.IndexOf(target);

    if (removedIdx == targetIdx)
        return;

    Memos.RemoveAt(removedIdx);
    Memos.Insert(targetIdx, droppedData);

    for (int i = 0; i < Memos.Count; i++)
    {
        _repo.UpdateOrder(Memos[i].Id, i);
    }
}

だいぶスッキリした!!

大した内容ではないですが、初めての記事投稿の練習ということで、
取り上げてみました。

このようにアウトプットしていきながら、スキルアップしていきたいと思います!

5
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?