我的问题是使用foreach我自己的链表添加处理。 我通过查看示例here
创建了我的链接列表我想将LINQ添加到我的链接列表中。哪里可以看到它?或者我如何实现它?
答案 0 :(得分:1)
You just need to implement IEnumerabe<object>
inside your LinkedList
class:
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:
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):
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;
}
}
}
答案 1 :(得分:0)
您的链接列表需要实现std::function
。
答案 2 :(得分:0)
You can implement a AsEnumerable()
to use linq
public IEnumerable<T> AsEnumerable<T>()
{
var current = root;
while (current != null)
{
yield return current;
current = current.NextNode;
}
}