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

前端 未结 6 1514
余生分开走
余生分开走 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:24

    Since IEnumerable is read-only, you need to convert to list.

    var new_one = arr.ToList().Add("JKL");
    

    Or you can get a extension method like;

    public static IEnumerable Append(this IEnumerable source, params T[] item)
    {
        return source.Concat(item);
    }
    

提交回复
热议问题