我如何添加一个项目到了IEnumerable< T>采集? [英] How can I add an item to a IEnumerable<T> collection?

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

问题描述

我作为标题上面的问题。例如,

My question as title above. For example,

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

但毕竟它只有1里面的物品。

but after all it only has 1 item inside.

我们能有像 items.Add的方法(项目)

列表&LT; T&GT;

推荐答案

您不能,因为的IEnumerable&LT; T&GT; 不一定再present收集到项可以被加入。事实上,它不一定再present集合了!例如:

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 (s != "");
}

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

你能做什么,但是,是创建的新的的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" });

此的不会改变数组对象的(你不能将物品进入到阵列,反正)。但它会创建一个新的对象,将列出阵列中的所有项目,然后在富。此外,新的对象的跟踪变化的阵列中的的(即每当你列举它,你会看到项目的当前值)。

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&LT; T&GT;采集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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