Shortcut for creating single item list in C#

前端 未结 13 1848
迷失自我
迷失自我 2020-12-14 05:06

In C#, is there an inline shortcut to instantiate a List with only one item.

I\'m currently doing:

new List( new string[] { \"         


        
13条回答
  •  执念已碎
    2020-12-14 05:47

    For a single item enumerable in java it would be Collections.singleton("string");

    In c# this is going to be more efficient than a new List:

    public class SingleEnumerator : IEnumerable
    {
        private readonly T m_Value;
    
        public SingleEnumerator(T value)
        {
            m_Value = value;
        }
    
        public IEnumerator GetEnumerator()
        {
            yield return m_Value;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            yield return m_Value;
        }
    }
    

    but is there a simpler way using the framework?

提交回复
热议问题