【问题标题】:Why IEnumerable<T> becomes empty after adding elements to a collection?为什么 IEnumerable<T> 在将元素添加到集合后变为空?
【发布时间】:2011-07-10 21:08:00
【问题描述】:
  • 我有一个IEnumerable&lt;T&gt;,当我遍历它并将它的元素添加到列表中时它变成空的?

  • 我对代码的期望通常有什么问题吗?

    public class Apple
    {
        private ICollection<Fruit> _fruits = new List<Fruit>();
    
        public void AddFruits(IEnumerable<Fruit> fruits)
        {
            if (fruits == null) throw new ArgumentNullException("fruits");
            foreach (var fruit in fruits)
            {
                _fruits.Add(fruit);
            }
        }
    }
    

    调用者代码:

    public void AddFruits(IEnumerable<Fruit> fruitsToAdd)
    {
        foreach (var apple in apples)
        {
            // Here fruitsToAdd has elements, fruitsToAdd.ToList() has two fruits.
            apple.AddFruits(fruitsToAdd);
            // Here fruitsToAdd has NO element!!, fruitsToAdd.ToList() is empty!
            // next iteration will not add any fruit to next apple since fruitsToAdd is empty.
        }
    }
    

更新

ToList() 解决了这个问题。问题的根源在于 AddFruits(IEnumerable fruitsToAdd) 的调用者发送了 fruitsToAdd 就像这样。

fruitsToAdd = obj.Fruits.Except(apples.Fruits);

每次 IEnumerable fruitsToAdd 是 Rest 它运行上面的语句。在下一次迭代中运行 except ,因此没有返回任何结果。

正确的做法是 fruitsToAdd = obj.Fruits.Except(apples.Fruits).ToList();因为我们想要一个评估。

【问题讨论】:

  • 因为你的代码有问题,我想。如果没有看到您的 任何 代码,很难再说什么...
  • 那么问题到底出在哪里?你能显示产生错误的代码吗?
  • 你还没有展示你的IEnumerable&lt;T&gt;实际上是什么。请给我们足够的代码来重现问题。
  • @Amir Rezaei,编写一个简单的(可编译的)控制台应用程序来说明您的问题。这样一切都会清楚。
  • @Amir Rezaei,您必须缩小问题范围。目前你的问题还不清楚。在您发布的代码的 cmets 中,您说 fruits 没有元素。但是fruitsToAdd 是一个IEnumerable&lt;T&gt;,而IEnumerable&lt;T&gt; 没有这种有或没有元素的概念。它只是指向您可以枚举的某些数据源的指针。而且您还没有表明它所指向的内容,也没有表明 it has elements 的含义。目前您的问题很难回答,因为您似乎是唯一能够重现某些问题的人。

标签: c# linq generics ienumerable


【解决方案1】:

好的,试试这个:

public void AddFruits(IEnumerable<Fruit> fruitsToAdd)
{
    var fruitsToAddCopy = fruitsToAdd.ToList();  // add just this line

    foreach (var apple in apples)
    {           
        apple.AddFruits(fruitsToAddCopy);    // and change this        
    }
}

如果不知道您的fruitsToAdd 的来源,就不可能再说更多。一些IEnumerable&lt;&gt; 不能重复使用。其他人可以。

【讨论】:

  • 为什么“有些 IEnumerable 不能重用。其他的可以。”
  • ToList() 解决了这个问题。问题是为什么?
  • 问题是:你传入的是什么?大多数 IEnumerables 可以重置,但它可能非常昂贵 (IQueryable)。我想不出一个记录为一次性使用的,来自网络流的东西。但是你的 Apple 类是无关紧要的,看看 AddFruits 的调用者。
  • @Henk:IEnumerable&lt;T&gt; 无法重置(通过界面)- 只有IEnumerator&lt;T&gt; 可以。
  • @Jon,对,用词草率。我会留下评论,我认为总体思路仍然成立。
【解决方案2】:

我修改了您的代码以使其能够编译并编写了一个测试。将元素复制到苹果后,您的列表不会为空。

    using System;
    using System.Collections.Generic;
    using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace ClassLibrary3
{
    [TestClass]
    public class Class1
    {
        [TestMethod]
        public void test()
        {
            var fruits = new List<Fruit> {new Fruit(), new Fruit(), new Fruit()};

            var lists = AddFruits(fruits);
            Assert.IsTrue(fruits.Count == 3);

        }

        public List<Apple> AddFruits(IEnumerable<Fruit> fruitsToAdd)
        {
            var apples = new List<Apple>
                             {
                                 new Apple(),
                                 new Apple()
                             };

            foreach (var apple in apples)
            {
                apple.AddFruits(fruitsToAdd);
            }
            return apples;
        }
    }

    public class Fruit 
    {
    }

    public class Apple
    {
        private ICollection<Fruit> _fruits = new List<Fruit>();

        public void AddFruits(IEnumerable<Fruit> fruits)
        {
            if (fruits == null) throw new ArgumentNullException("fruits");
            foreach (var fruit in fruits)
            {
                _fruits.Add(fruit);
            }
        }
    }
}

【讨论】:

  • 那么问题出在Fruit的实现上?
【解决方案3】:

您问题中的代码不应表现出这种行为,因此我假设您尝试简化它,但从中删除了很多功能。

看起来有点可疑的是您的_fruits 字段的类型为ICollection&lt;T&gt;。此接口通常与自定义集合实现一起使用。是否有可能,在实际代码中,该字段没有使用List&lt;T&gt; 进行实例化,而是使用该接口的自定义实现?

如果你有一个自定义集合实现,那么它的Add 方法完全有可能做一些奇怪的事情(比如在将它添加到新的“父”集合之前从其先前的“父”集合中删除一个项目)。树集合经常做这样的事情来简化移动节点。

[编辑]

我知道这不是 OP 的实际问题,但我仍然会添加一个示例来演示自定义集合实现可以实际上在其成员添加到不同的输入集合时修改输入集合收藏。

假设Fruit 类如下所示:

partial class Fruit
{
    private ICollection<Fruit> _children;
    private Fruit _parent;

    public String Name { get; set; }

    public Fruit()
    {
        _children = new FruitCollection(this);
    }

    public void AddFruits(IEnumerable<Fruit> fruits)
    {
        foreach (Fruit f in fruits)
            _children.Add(f);
    }

    public int NumberOfChildren
    {
        get { return _children.Count; }
    }

    public IEnumerable<Fruit> GetFruits()
    {
        return _children.ToList();
    }
}

还有一个自定义集合定义为:

partial class Fruit
{
    public class FruitCollection : Collection<Fruit>
    {
        private readonly Fruit _parent;
        public FruitCollection(Fruit parent)
        {
            _parent = parent;
        }

        protected override void InsertItem(int index, Fruit item)
        {
            // item already has a parent?
            if (item._parent != null)
            {
                // remove it from previous parent
                item._parent._children.Remove(item);
            }

            // set the new parent
            item._parent = _parent;

            base.InsertItem(index, item);
        }

        // other methods should be overriden in a similar way
    }
}

然后是下面的程序:

static void Main(string[] args)
{
    List<Fruit> abc = new List<Fruit>()
    {
        new Fruit() { Name = "a" },
        new Fruit() { Name = "b" },
        new Fruit() { Name = "c" }
    };

    Fruit apple = new Fruit() { Name = "apple" };
    apple.AddFruits(abc);

    Console.WriteLine("{0} has {1} children", apple.Name, apple.NumberOfChildren);


    // now try to add apples's children to
    // each of the following fruits
    List<Fruit> def = new List<Fruit>()
    {
        new Fruit() { Name = "d" },
        new Fruit() { Name = "e" },
        new Fruit() { Name = "f" }
    };

    foreach (Fruit f in def)
    {
        f.AddFruits(apple.GetFruits());
        Console.WriteLine("{0} has {1} children", f.Name, f.NumberOfChildren);
    }

    Console.Read();
}

将打印:

苹果有3个孩子 d 有 3 个孩子 e有0个孩子 f 有 0 个孩子

因为apple.GetFruits() 在第一次迭代后会返回 0。

通过查看自定义集合的来源,很难发现AddFruits 中的_children.Add(f) 实际上修改了fruits 先前的父集合。

【讨论】:

  • 该列表是一个 .Net 列表。这不是自定义实现。
  • 不错的猜测,但 _fruits 不是问题。 fruitsToAdd 是。
猜你喜欢
  • 1970-01-01
  • 2013-01-24
  • 2010-11-15
  • 2013-08-22
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多