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

扶醉桌前 提交于 2019-11-29 16:10:12

问题


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

//Some IEnumerable<T> object
IEnumerable<string> arr = new string[] { "ABC", "DEF", "GHI" };

//Add one item
arr = arr.Concat(new string[] { "JKL" });

This is awkward. I don't see a method called something like ConcatSingle() however.

Is there a cleaner way to add a single item to an IEnumerable object?


回答1:


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<T> Append<T>(
        this IEnumerable<T> source, params T[] tail)
    {
        return source.Concat(tail);
    }
}



回答2:


IEnumerable is immutable collection, it means you cannot add, or remove item. Instead, you have to create a new collection for this, simply to convert to list to add:

var newCollection = arr.ToList();
newCollection.Add("JKL"); //is your new collection with the item added



回答3:


Write an extension method ConcatSingle :)

public static IEnumerable<T> ConcatSingle<T>(this IEnumerable<T> 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<T>. Concat creates a new instance.

Example:

var items = Enumerable.Range<int>(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.




回答4:


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<T> Append<T>(this IEnumerable<T> source, params T[] item)
{
    return source.Concat(item);
}



回答5:


You're assigning an array to an IEnumerable. Why don't you use the Array type instead of IEnumerable?

Otherwise you can use IList (or List) if you want to change the collection.

I use IEnumerable only for methods params when I need to read and IList (or List) when I need to change items in it.



来源:https://stackoverflow.com/questions/15251159/whats-the-best-way-to-add-one-item-to-an-ienumerablet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!