What's the Best Way to Add One Item to an IEnumerable?

前端 未结 6 1527
余生分开走
余生分开走 2021-01-01 09:43

Here\'s how I would add one item to an IEnumerable object:

//Some IEnumerable object
IEnumerable arr = new string[] { \"ABC\", \"DEF\"         


        
6条回答
  •  没有蜡笔的小新
    2021-01-01 10:22

    Nope, that's about as concise as you'll get using built-in language/framework features.

    You could always create an extension method if you prefer:

    arr = arr.Append("JKL");
    // or
    arr = arr.Append("123", "456");
    // or
    arr = arr.Append("MNO", "PQR", "STU", "VWY", "etc", "...");
    
    // ...
    
    public static class EnumerableExtensions
    {
        public static IEnumerable Append(
            this IEnumerable source, params T[] tail)
        {
            return source.Concat(tail);
        }
    }
    

提交回复
热议问题