Frage

I am designing a Graph class (both list and matrix implementations). I have to provide method such as GetAdjacencies(int vertex).

In the first moment I thought of returning IEnumerable and that way I will be able to iterate through the result using foreach statement. But in the next moment, I realized it is horrible solution because new list must be created each time GetAdjacencies(int vertex) occurs.

Next I thought of returning Enumerator, but that way I can't iterate through the result using foreach statement. However efficiency is much better (I will implement many graph algorithms and I am really interested in optimization).

Could you tell me what is the right way to do this in C#?

War es hilfreich?

Lösung

You don't have to create new list each time the method is called. Use iterator blocks for instance:

public IEnumerable<int> GetAdjacencies(int vertex)
{
    foreach (int i in adj[vertex])
        yield return i;
}

I don't know how exactly the graph is represented in your code, so the details of getting adjacencies list may vary.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top