我的问题如上所述。例如

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

但毕竟里面只有一项。我们能不能有一个items.Add(item)方法,比如List<T>?


当前回答

不能,因为IEnumerable<T>不一定表示可以添加项的集合。事实上,它并不一定代表一个集合!例如:

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??

但是,您可以创建一个新的IEnumerable对象(未指定类型),当它被枚举时,将提供旧对象的所有项,以及您自己的一些项。你使用Enumerable。为此Concat:

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

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

其他回答

一对简短,甜蜜的扩展方法IEnumerable和IEnumerable<T>做它为我:

public static IEnumerable Append(this IEnumerable first, params object[] second)
{
    return first.OfType<object>().Concat(second);
}
public static IEnumerable<T> Append<T>(this IEnumerable<T> first, params T[] second)
{
    return first.Concat(second);
}   
public static IEnumerable Prepend(this IEnumerable first, params object[] second)
{
    return second.Concat(first.OfType<object>());
}
public static IEnumerable<T> Prepend<T>(this IEnumerable<T> first, params T[] second)
{
    return second.Concat(first);
}

优雅(好吧,非通用版本除外)。可惜这些方法不在BCL中。

要添加第二条消息,您需要-

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

很抱歉,我又提了一个老问题,但由于它出现在谷歌搜索结果的第一个列表中,我想有些人会一直登陆这里。

在许多答案中,其中一些非常有价值,并且解释得很好,我想补充一个不同的观点,因为对我来说,问题还没有很好地确定。

你正在声明一个存储数据的变量,你需要它能够通过添加项目来改变吗?所以你不应该把它声明为IEnumerable。

由@NightOwl888提议

对于本例,只需声明IList而不是IEnumerable: IList items = new T[]{new T("msg")};物品。添加(新T(“msg2”));

试图绕过声明的接口限制只表明您做出了错误的选择。 除此之外,所有提议用来实现其他实现中已经存在的东西的方法都应该考虑。 允许您添加项的类和接口已经存在。为什么总是复制别人已经做过的东西?

这种考虑是在接口中抽象变量功能的目标。

TL;DR:在我看来,这些是做你需要的事情的最干净的方法:

// 1st choice : Changing declaration
IList<T> variable = new T[] { };
variable.Add(new T());

// 2nd choice : Changing instantiation, letting the framework taking care of declaration
var variable = new List<T> { };
variable.Add(new T());

当您需要使用变量作为IEnumerable时,您将能够。当你需要将它作为数组使用时,你可以调用'ToArray()',它总是应该这么简单。不需要扩展方法,仅在真正需要时才强制转换,能够在变量上使用LinQ,等等…

停止做奇怪和/或复杂的事情,因为你只是在声明/实例化时犯了一个错误。

也许我说得太迟了,但我希望这对将来的任何人都有帮助。

可以使用insert函数在特定索引处添加项。 列表。插入(0项);

不,IEnumerable不支持向它添加项目。另一种解决方案是

var myList = new List(items);
myList.Add(otherItem);