C# 添加到 IEnumerable 的代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15760870/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 17:52:07  来源:igfitidea点击:

Code for adding to IEnumerable

c#ienumerableadd

提问by Sudha

I have an enumerator like this

我有一个这样的枚举器

IEnumerable<System.Windows.Documents.FixedPage> page;

How can I add a page (eg: D:\newfile.txt) to it? I have tried Add, Append, Concatetc But nothing worked for me.

如何向其中添加页面(例如:D:\newfile.txt)?我已经试过AddAppendConcat等但没有为我工作。

采纳答案by Matthew Watson

Yes, it is possible

对的,这是可能的

It is possible to concatenate sequences (IEnumerables) together and assign the concatenated result to a new sequence. (You cannot change the original sequence.)

可以将序列 (IEnumerables) 连接在一起并将连接的结果分配给新序列。(您不能更改原始顺序。)

The built-in Enumerable.Concat()will only concatenate another sequence; however, it is easy to write an extension method that will let you concatenate a scalar to a sequence.

内置Enumerable.Concat()函数只会连接另一个序列;然而,很容易编写一个扩展方法,让您将一个标量连接到一个序列。

The following code demonstrates:

以下代码演示:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Demo
{
    public class Program
    {
        [STAThread]
        private static void Main()
        {
            var stringList = new List<string> {"One", "Two", "Three"};

            IEnumerable<string> originalSequence = stringList;

            var newSequence = originalSequence.Concat("Four");

            foreach (var text in newSequence)
            {
                Console.WriteLine(text); // Prints "One" "Two" "Three" "Four".
            }
        }
    }

    public static class EnumerableExt
    {
        /// <summary>Concatenates a scalar to a sequence.</summary>
        /// <typeparam name="T">The type of elements in the sequence.</typeparam>
        /// <param name="sequence">a sequence.</param>
        /// <param name="item">The scalar item to concatenate to the sequence.</param>
        /// <returns>A sequence which has the specified item appended to it.</returns>
        /// <remarks>
        /// The standard .Net IEnumerable extensions includes a Concat() operator which concatenates a sequence to another sequence.
        /// However, it does not allow you to concat a scalar to a sequence. This operator provides that ability.
        /// </remarks>

        public static IEnumerable<T> Concat<T>(this IEnumerable<T> sequence, T item)
        {
            return sequence.Concat(new[] { item });
        }
    }
}

回答by Mark Broadhurst

IEnumerable<T>does not contain a way to modify the collection.

IEnumerable<T>不包含修改集合的方法。

You will need to implement either ICollection<T>or IList<T>as these contain an Add and Remove functions.

您将需要实现其中一个ICollection<T>IList<T>因为它们包含添加和删除功能。

回答by Fredrik M?rk

IEnumerable<T>is a readonly interface. You should use an IList<T>instead, which provides methods for adding and removing items.

IEnumerable<T>是一个只读接口。您应该使用IList<T>替代,它提供了添加和删除项目的方法。

回答by bash.d

IEnumerableis immutable. You can't add items, you can't delete items.
The classes from System.Collections.Genericreturn this interface so you can iterate over the items contained in the collection.

IEnumerable是不可变的。您无法添加项目,也无法删除项目。
来自的类System.Collections.Generic返回此接口,因此您可以迭代集合中包含的项目。

From MSDN

来自 MSDN

Exposes the enumerator, which supports a simple iteration over a collection of a specified type.

See herefor MSDN reference.

请参阅此处以获取 MSDN 参考。

回答by Ivaylo Slavov

You cannot add elements to IEnumerable<T>, since it does not support addition operations. You either have to use an implementation of ICollection<T>, or cast the IEnumerable<T>to ICollection<T>if possible.

您不能向 中添加元素IEnumerable<T>,因为它不支持添加操作。你要么必须使用的实现ICollection<T>,或施放IEnumerable<T>ICollection<T>如果可能的话。

IEnumerable<System.Windows.Documents.FixedPage> page;
....
ICollection<System.Windows.Documents.FixedPage> pageCollection 
    = (ICollection<System.Windows.Documents.FixedPage>) page

If the cast is impossible, use for instance

如果演员是不可能的,例如使用

ICollection<System.Windows.Documents.FixedPage> pageCollection 
   = new List<System.Windows.Documents.FixedPage>(page);

You can do it like this:

你可以这样做:

ICollection<System.Windows.Documents.FixedPage> pageCollection
    = (page as ICollection<System.Windows.Documents.FixedPage>) ??
      new List<System.Windows.Documents.FixedPage>(page);

The latter will almost guarantee that you have a collection that is modifiable. It is possible, though, when using cast, to successfully get the collection, but all modification operations to throw NotSupportedException. This is so for read-only collections. In such cases the approach with the constructor is the only option.

后者几乎可以保证您拥有一个可修改的集合。但是,在使用 cast 时有可能成功获取集合,但所有修改操作都为 throw NotSupportedException。对于只读集合也是如此。在这种情况下,构造函数的方法是唯一的选择。

The ICollection<T>interface implements IEnumerable<T>, so you can use pageCollectionwherever you are currently using page.

ICollection<T>接口实现IEnumerable<T>,所以你可以使用pageCollection任何你正在使用page

回答by evgenyl

Try

尝试

IEnumerable<System.Windows.Documents.FixedPage> page = new List<System.Windows.Documents.FixedPage>(your items list here)

or

或者

IList<System.Windows.Documents.FixedPage> page = new List<System.Windows.Documents.FixedPage>(1);
page.Add(your item Here);

回答by Steve

If you have an idea of what the original type of the IEnumerable is, you can modify it...

如果你知道 IEnumerable 的原始类型是什么,你可以修改它......

List<string> stringList = new List<string>();
stringList.Add("One");
stringList.Add("Two");
IEnumerable<string> stringEnumerable = stringList.AsEnumerable();
List<string> stringList2 = stringEnumerable as List<string>;

if (stringList2 != null)
    stringList2.Add("Three");

foreach (var s in stringList)
    Console.WriteLine(s);

This outputs:

这输出:

One
Two
Three

Change the foreach statement to iterate over stringList2, or stringEnumerable, you'll get the same thing.

将 foreach 语句更改为迭代stringList2,或者stringEnumerable,您将得到相同的结果。

Reflection might be useful to determine the realtype of the IEnumerable.

反射可能有助于确定IEnumerable的真实类型。

This probably isn't a good practice, though... Whatever gave you the IEnumerable is probably not expecting the collection to be modified that way.

不过,这可能不是一个好的做法……无论给您 IEnumerable 什么,都可能不希望以这种方式修改集合。