How can I add an item to a IEnumerable collecti

2019-01-02 19:18发布

My question as title above. For example,

IEnumerable<T> items = new T[]{new T("msg")};
items.ToList().Add(new T("msg2"));

but after all it only has 1 item inside.

Can we have a method like items.Add(item)?

like the List<T>

13条回答
残风、尘缘若梦
2楼-- · 2019-01-02 19:50

Have you considered using ICollection<T> or IList<T> interfaces instead, they exist for the very reason that you want to have an 'Add' method on an IEnumerable<T>. IEnumerable<T> is used to 'mark' a type as being ...well.. enumerable or just a sequence of items without necessarily making any guarantees of whether the real underlying object supports adding/removing of items. Also remember that these interfaces implements IEnumerable<T> so you get all the extensions methods that you get with IEnumerable<T> as well.

查看更多
无与为乐者.
3楼-- · 2019-01-02 19:50

To add second message you need to -

IEnumerable<T> items = new T[]{new T("msg")};
items = items.Concat(new[] {new T("msg2")})
查看更多
爱死公子算了
4楼-- · 2019-01-02 19:58

Easyest way to do that is simply

IEnumerable<T> items = new T[]{new T("msg")};
List<string> itemsList = new List<string>();
itemsList.AddRange(items.Select(y => y.ToString()));
itemsList.Add("msg2");

Then you can return list as IEnumerable also because it implements IEnumerable interface

查看更多
大哥的爱人
5楼-- · 2019-01-02 20:03

In .net Core, there is a method Enumerable.Append that does exactly that.

The source code of the method is available on GitHub..... The implementation (more sophisticated than the suggestions in other answers) is worth a look :).

查看更多
情到深处是孤独
6楼-- · 2019-01-02 20:03

you can do this.

//Create IEnumerable    
IEnumerable<T> items = new T[]{new T("msg")};

//Convert to list.
List<T> list = items.ToList();

//Add new item to list.
list.add(new T("msg2"));

//Cast list to IEnumerable
items = (IEnumerable<T>)items;
查看更多
何处买醉
7楼-- · 2019-01-02 20:09

Others have already given great explanations regarding why you can not (and should not!) be able to add items to an IEnumerable. I will only add that if you are looking to continue coding to an interface that represents a collection and want an add method, you should code to ICollection or IList. As an added bonanza, these interfaces implement IEnumerable.

查看更多
登录 后发表回答