gpt4 book ai didi

c# - LINQ,创建集合的唯一集合

转载 作者:太空狗 更新时间:2023-10-29 21:46:17 25 4
gpt4 key购买 nike

我有

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
}
}

EdgesVertexes被收集到列表中

一些例子:

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

所以我想制作IDictionary<Edge, bool>它将保持边缘(A-->B 和 B-->A 就像 1),以及 bool - 如果它是双向的或否。

我需要它,因为当我现在绘制它们时,它会在彼此下方绘制 2 个箭头。我最好做 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());
}
}

并将你的边添加到 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());
}
}

并用

初始化你的哈希集
_drawableEdges = new HashSet<Edge>(EdgeComparer.Default);

关于c# - LINQ,创建集合的唯一集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9894442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com