[英]How to add functionality of treatment to my own linked list
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.