【问题标题】:How to add functionality of treatment to my own linked list如何将治疗功能添加到我自己的链表中
【发布时间】:2015-07-01 02:11:25
【问题描述】:

我的问题是用 foreach 添加我自己的链表。 我通过查看示例 here

创建了我的链接列表

我想将 LINQ 添加到我的链接列表中。我在哪里可以看到它?或者我如何实现它?

【问题讨论】:

    标签: c# singly-linked-list


    【解决方案1】:

    你可以实现一个AsEnumerable() 来使用linq

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

    【讨论】:

      【解决方案2】:

      您只需要在 LinkedList 类中实现 IEnumerabe&lt;object&gt;

      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();
              }
      }
      

      然后,Linq 将起作用:

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

      至于 IEnumerable 实现是惰性评估 (yield return),您可能希望在迭代时修改列表时抛出异常(以防止错误或某事):

      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;
               } 
          }
      }
      

      【讨论】:

        【解决方案3】:

        你的链表需要实现IEnumerable&lt;T&gt;

        【讨论】:

        • 我需要重写所有我需要的功能代码吗?
        • 不,你只需要实现 IEnumerable 的唯一方法 GetEnumerator(见 pwas 的回答)。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-06-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-02
        相关资源
        最近更新 更多