简体   繁体   中英

Java Collection in C#

I'm learning some data structures and the language of the course is Java but I'm a C# guy.

Here is the code:

public Collection <Vertex> vertices()
{ 
     return graph.values(); 
}

Vertex is a class but how can I return a Collection in C#? Ty!  

Edit: I don't know if it will help but here is the class Vertex.(Code already in C#) Comments are in german.

public class Vertex : IComparable //Knotenklasse 
{
    public string name; // Name des Knoten
    public List<Edge> edges; // Nachbarn als Kantenliste
    public int nr; // Knotennummer
    public int indegree; // Eingangsgrad
    public bool seen; // Wurde der Knoten schon überprüft? 
    public int dist; // Kosten für den Knoten
    public Vertex prev; // vorheriger Knoten

    public Vertex(string s)
    {
        this.name = s;
        edges = new List<Edge>(); 
    }

    public bool hasEdge(Vertex w)
    {
        foreach (Edge e in edges)
        {
            if(e.dest == w)
            {
                return true;
            }

        }
        return false; 
    }

    public int CompareTo(Vertex d)
    {
       if(this.dist > d.dist)
       {
           return 1;
       }
       else if(this.dist < d.dist)
       {
           return -1;
       }
       else
       {
           return 0; 
       }
    }
}
public class Edge // Kantenklasee
{
    public double cost; // Kosten
    public Vertex dest; // Zeiger auf den nächsten Knoten

    public Edge(Vertex d,double c)
    {
        this.dest = d;
        this.cost = c; 
    }
}

ps: the class graph in C#

public class Graph
{
        private Dictionary<Vertex, string> graph;  
        public Graph(Vertex d, string s)
        {
            graph = new Dictionary<Vertex, string>(); 
        }

}

Dictionary.Values returns a ValueCollection . You can use it directly or convert it to many built in collection types in .NET.

Generally you should return a type that is as general as possible, ie one that knows just enough of the returned data.

public ICollection<Vertex> vertices()
{ 
    return graph.values(); 
}

public IList<Vertex> vertices()
{ 
    return graph.values().ToList(); 
}

ICollection<T> supports Add , Remove and Count .
IList<T> supports Add , Remove , Count and the ability to random access elements by their indexes

If you want to know more about different collection types and when to use them check this link

You can use ICollection<T> which is an generic interface implemented by all the classes from System.Collections.generic :

public ICollection<Vertex> vertices()
{ 
     return graph.values(); 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM