如何将处理功能添加到我自己的链表中
How to add functionality of treatment to my own linked list
我的问题是添加 treat with foreach 我自己的链表。
我通过查看示例 here
创建了我的链表
并且我想将 LINQ 添加到我的链表中。我在哪里可以看到它?或者我该如何实施?
你的链表需要实现IEnumerable<T>
.
您只需要在 LinkedList
class:
中实现 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();
}
}
然后,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;
}
}
}
您可以实施 AsEnumerable()
以使用 linq
public IEnumerable<T> AsEnumerable<T>()
{
var current = root;
while (current != null)
{
yield return current;
current = current.NextNode;
}
}
我的问题是添加 treat with foreach 我自己的链表。 我通过查看示例 here
创建了我的链表并且我想将 LINQ 添加到我的链表中。我在哪里可以看到它?或者我该如何实施?
你的链表需要实现IEnumerable<T>
.
您只需要在 LinkedList
class:
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();
}
}
然后,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;
}
}
}
您可以实施 AsEnumerable()
以使用 linq
public IEnumerable<T> AsEnumerable<T>()
{
var current = root;
while (current != null)
{
yield return current;
current = current.NextNode;
}
}