Shortcut for creating single item list in C#

前端 未结 13 1844
迷失自我
迷失自我 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:43

    Yet another way, found on "C#/.Net Little wonders" (unfortunately, the site doesn't exist anymore):

    Enumerable.Repeat("value",1).ToList()
    
    0 讨论(0)
  • 2020-12-14 05:43

    I would just do

    var list = new List<string> { "hello" };
    
    0 讨论(0)
  • 2020-12-14 05:45
    var list = new List<string>(1) { "hello" };
    

    Very similar to what others have posted, except that it makes sure to only allocate space for the single item initially.

    Of course, if you know you'll be adding a bunch of stuff later it may not be a good idea, but still worth mentioning once.

    0 讨论(0)
  • 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<T> : IEnumerable<T>
    {
        private readonly T m_Value;
    
        public SingleEnumerator(T value)
        {
            m_Value = value;
        }
    
        public IEnumerator<T> GetEnumerator()
        {
            yield return m_Value;
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            yield return m_Value;
        }
    }
    

    but is there a simpler way using the framework?

    0 讨论(0)
  • 2020-12-14 05:52

    Michael's idea of using extension methods leads to something even simpler:

    public static List<T> InList<T>(this T item)
    {
        return new List<T> { item };
    }
    

    So you could do this:

    List<string> foo = "Hello".InList();
    

    I'm not sure whether I like it or not, mind you...

    0 讨论(0)
  • 2020-12-14 06:00

    I've got this little function:

    public static class CoreUtil
    {    
        public static IEnumerable<T> ToEnumerable<T>(params T[] items)
        {
            return items;
        }
    }
    

    Since it doesn't prescribe a concrete return type this is so generic that I use it all over the place. Your code would look like

    CoreUtil.ToEnumerable("title").ToList();
    

    But of course it also allows

    CoreUtil.ToEnumerable("title1", "title2", "title3").ToArray();
    

    I often use it in when I have to append/prepend one item to the output of a LINQ statement. For instance to add a blank item to a selection list:

    CoreUtil.ToEnumerable("").Concat(context.TrialTypes.Select(t => t.Name))
    

    Saves a few ToList() and Add statements.

    (Late answer, but I stumbled upon this oldie and thought this could be helpful)

    0 讨论(0)
提交回复
热议问题