Domanda

Would there be any problems if I did the following to imitate a liked list using a list.

Create a class like this

public class MyClass
{
 //some properties
 public MyClass Previous {get; set;}
 public MyClass Next {get; set;}
}

and add this to a generic List.

I only add elements to this list and never remove them.

I am not using the .Net LinkedList class as I had overlooked the Previous property of the LinkedListNode class. I was in a hurry to get things working.

The way I am using this class is mostly by using the ForEach extension of the List.

List<MyClass> MyList = new List<MyClass>();

//add some elements with Previous,Next set

MyList.Foreach(CalculateValues);

CalculateValues(MyClass current)
{
  MyClass prev = current.Previous; 
  //check for null and return etc
  //In some moethods I use Next
  current.SomeProperty += prev.SomeProperty; 
}

I see that the LinkedList has no ForEach method though. I could still iterate using ForEach loop. Thanks for all the great answers.

È stato utile?

Soluzione

Yes, you would be violating the Single Responsibility Principle by using the same class to represent both a Collection of an item and the item itself. And you wouldn't be making use of the perfectly-good classes that come standard with the .NET library, like LinkedList<T>.

Altri suggerimenti

You should at least include some Item property

public class MyClass<T>
{
 //some properties
 public MyClass Previous {get; set;}
 public MyClass Next {get; set;}
 public T Item {get; set;}
}

The I would suggest to implement IEnumerable too to get some iterating functionality. IList seems reasonable too. But why not use the Built in LinkedList?

Your issue isn't with using a Generic List to store your items. It's the fact that your class is storing the Previous/Next items rather than just data about itself. You'd never be able to re-use the Linked List implementation.

You should have something to store a Node in the Linked List:

public class LinkedList<T>
{
    private List<LinkedListNode<T>> nodes = new List<LinkedListNode<T>>();
}

public class LinkedListNode<T>
{
    public LinkedListNode<T> Previous { get; set; }
    public LinkedListNode<T> Next { get; set; }
    public T Item { get; set; }
}

public class MyClass
{
    // Some Properties
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top