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

前端 未结 6 1509
余生分开走
余生分开走 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-01 10:24

    Write an extension method ConcatSingle :)

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

    But you need to be more careful with your terminology.
    You can't add an item to an IEnumerable. Concat creates a new instance.

    Example:

    var items = Enumerable.Range(1, 10)
    Console.WriteLine(items.Count()); // 10
    var original= items;
    items = items.ConcatSingle(11);
    Console.WriteLine(original.Count());   // 10
    Console.WriteLine(items.Count()); // 11
    

    As you can see, the original enumeration - which we saved in original didn't change.

提交回复
热议问题