Wis*_*ish 6 c# linq ienumerable
我有
class Vertex{
Graph _graph;
float x;
float y;
string key;
//and some similar atributes
public IEnumerable<Edge> Edges{
get{
return _graph.Edges.Where(s => s.Source == this);
}
}
}
class Edge{
Graph _graph;
Vertex source;
Vertex target;
}
class Graph
{
private VertexCollection _vertexCollection; // extends List<Vertex>
private EdgeCollection _edgeCollection; //extends List<Edge>
public IEnumerable<Vertex> Vertexes
{
get
{
return _vertexCollection;
}
}
public IEnumerable<Edge> Edges
{
get
{
return _edgeCollection;
}
}
public IDictionary<Edge, bool> DrawableEdges
{
get
{
//want to return my uniq dictionary
}
}
Run Code Online (Sandbox Code Playgroud)
Edges并被Vertexes收集到列表中
一些例子:
A-->B // edge from vertex A to B
B-->C // edge from vertex B to C
C-->A // edge from vertex C to A
A-->C // edge from vertex A to C -- this is two way edge
Run Code Online (Sandbox Code Playgroud)
所以我想制作IDictionary<Edge, bool>哪个会保持边缘(A - > B和B - > A就像1),然后布尔 - 如果它是双向的或者不是.
我需要它,因为当我现在画它们时,它会在彼此之间绘制两个箭头.我最好制作1支箭.
所以我非常卡在这里......可能有人帮我一点吗?
IEquatable我认为你应该为你的类实现接口Edge:
public class Edge : IEquatable<Edge>
{
...
public bool Equals(Edge other)
{
return (
(other.Source == this.Source && other.Target == this.Target) ||
(other.Target == this.Source && other.Source == this.Target));
}
public override int GetHashCode()
{
return (Source.GetHashCode() ^ Target.GetHashCode());
}
}
Run Code Online (Sandbox Code Playgroud)
并将您的边缘添加到HashSet<Edge>集合中。然后你可以调用它的Contains方法来检查它是否包含边缘。
编辑:就像 Henk 所说,您还可以实现自定义IEqualityComparer类:
public sealed class EdgeComparer : IEqualityComparer<Edge>
{
public static EdgeComparer Default { get; private set; }
static EdgeComparer()
{
Default = new EdgeComparer();
}
private EdgeComparer()
{
}
public bool Equals(Edge x, Edge y)
{
return (
(x.Source == y.Source && x.Target == y.Target) ||
(x.Target == y.Source && x.Source == y.Target));
}
public int GetHashCode(Edge edge)
{
return (edge.Source.GetHashCode() ^ edge.Target.GetHashCode());
}
}
Run Code Online (Sandbox Code Playgroud)
并初始化你的哈希集
_drawableEdges = new HashSet<Edge>(EdgeComparer.Default);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
156 次 |
| 最近记录: |