c# - How to add functionality of treatment to my own linked list -
my question add treat foreach own linked list. created linked list seeing example here
and want add linq linked list. can see it? or how can implement it?
you need implement ienumerabe<object>
inside linkedlist
class:
public class linkedlist : ienumerable<object> { // 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
work:
var result = mylinkedlist.where(data => /* condition */) .select(data => data.tostring();
as far ienumerable
implementation lazy evaluted (yield return
) want throw exception when list modified while itering (to prevent bugs or sth):
public class linkedlist : ienumerable<object> { long version = 0; public void add(object data) //it required methods 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 modified"); yield return current.data; current = current.next; } } }