简体   繁体   English

如何将治疗功能添加到我自己的链表中

[英]How to add functionality of treatment to my own linked list

My question is to add treat with foreach my own linked list. 我的问题是在我自己的链表中添加foreach。 I created my linked list by seeing example here 我通过看实例创建了链接列表在这里

And I want to add LINQ to my linked list. 我想将LINQ添加到我的链表中。 Where i can see it? 我在哪里可以看到它? Or how i can implement it? 还是我可以实现它?

You just need to implement IEnumerabe<object> inside your LinkedList class: 您只需要在LinkedList类中实现IEnumerabe<object>

public class LinkedList : IEnumerable<object>
{
        // your code
        // ....

        public IEnumerator<object> GetEnumerator()
        {
            var current = this.head;

            while (current != null)
            {
                yield return current.data;
                current = current.next;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
}

Then, Linq will work: 然后, Linq将工作:

var result = myLinkedList.Where(data => /* some condition */)
                         .Select(data => data.ToString();

As far as IEnumerable implementation is lazy evaluted ( yield return ) you would want to throw exception when list was modified while itering (to prevent bugs or sth): IEnumerable实现的延迟评估( yield return )而言,当您在迭代过程中修改list时,您想抛出异常(以防止bug或其他):

public class LinkedList : IEnumerable<object>
{
     long version = 0;

     public void Add(object data) //it is required for all
                                  methods that modyfies collection
     {
         // yout code
         this.vesion += 1;
     }

     public IEnumerator<object> GetEnumerator()
     {
         var current = this.head;
         var v = this.version;

         while (current != null)
         {            
              if (this.version != v) 
                  throw new InvalidOperationException("Collection was modified");

              yield return current.data;
              current = current.next;
         } 
    }
}

您的链表需要实现IEnumerable<T>

You can implement a AsEnumerable() to use linq 您可以实现一个AsEnumerable()以使用linq

public IEnumerable<T> AsEnumerable<T>()
{
    var current = root;
    while (current != null)
    {
        yield return current;
        current = current.NextNode;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM