본문 바로가기
프로그래밍/C#

C# foreach 중 삭제(Remove) feat Linq

by neive 2021. 2. 2.
728x90
    using System.Linq;

    Dictionary<string, float> m_Dic = new Dictionary<string, float>();

    private void Start()
    {
        m_Dic.Add("test1", 1.0f);
        m_Dic.Add("test2", 2.0f);
        m_Dic.Add("test3", 3.0f);

        // error
        foreach (var tmp in m_Dic)
            if (tmp.Value < 2.0f)
                m_Dic.Remove(tmp.Key);

        // success
        foreach (var key in m_Dic.Keys.ToList())
            if (m_Dic[key] < 2.0f)
                m_Dic.Remove(key);
    }
728x90

댓글