如何将项目添加到 IEnumerable<T>收藏? [英] How can I add an item to a IEnumerable&lt;T&gt; collection?

查看:24
本文介绍了如何将项目添加到 IEnumerable<T>收藏?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题作为上面的标题.例如

My question as title above. For example

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

但毕竟里面只有1个项目.我们可以像 List 那样有一个像 items.Add(item) 这样的方法吗?

but after all it only has 1 item inside. Can we have a method like items.Add(item) like the List<T>?

推荐答案

你不能,因为 IEnumerable 不一定代表可以添加项目的集合.事实上,它并不一定代表一个集合!例如:

You cannot, because IEnumerable<T> does not necessarily represent a collection to which items can be added. In fact, it does not necessarily represent a collection at all! For example:

IEnumerable<string> ReadLines()
{
     string s;
     do
     {
          s = Console.ReadLine();
          yield return s;
     } while (!string.IsNullOrEmpty(s));
}

IEnumerable<string> lines = ReadLines();
lines.Add("foo") // so what is this supposed to do??

然而,您可以做的是创建一个 new IEnumerable 对象(未指定类型),该对象在枚举时将提供旧对象的所有项目,加上一些你自己的.你使用 Enumerable.Concat :

What you can do, however, is create a new IEnumerable object (of unspecified type), which, when enumerated, will provide all items of the old one, plus some of your own. You use Enumerable.Concat for that:

 items = items.Concat(new[] { "foo" });

不会改变数组对象(无论如何你不能将项目插入到数组中).但它会创建一个新对象,列出数组中的所有项目,然后是Foo".此外,该新对象将跟踪数组中的变化(即,无论何时枚举它,您都会看到项目的当前值).

This will not change the array object (you cannot insert items into to arrays, anyway). But it will create a new object that will list all items in the array, and then "Foo". Furthermore, that new object will keep track of changes in the array (i.e. whenever you enumerate it, you'll see the current values of items).

这篇关于如何将项目添加到 IEnumerable<T>收藏?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆