如果嵌套的int[]
包含坐标x,y,我如何使用SequenceEqual比较它们?
列表是一组坐标。我想检查每个其他List以查看它们是否具有相同数量的坐标以及相同的坐标值。如果它们都匹配,我想删除多余的。否则,留下它。
private List<List<int[]>> combineList(List<List<int[]>> matches){
Debug.Log (matches.Count());
foreach(List<int[]> tileGroup in matches){
foreach(List<int[]> other in matches){
if(other == tileGroup) continue;
if(sequenceEqual(tileGroup, other)){
matches.Remove(other);
}
}
}
Debug.Log (matches.Count());
return matches;
}
private bool sequenceEqual(List<int[]> groupA, List<int[]> groupB){
if(groupA.Count() == groupB.Count()){
int i = 0, j = 0;
Dictionary<int, int[]> dictA = new Dictionary<int, int[]>(),
dictB = new Dictionary<int, int[]>();
foreach(int[] coordinate in groupA){
dictA.Add (i, coordinate);
i++;
}
foreach(int[] coordinate in groupB){
dictB.Add (j, coordinate);
j++;
}
return dictA.Values.SequenceEqual(dictB.Values);
}
return false;
}
答案 0 :(得分:1)
可能最快的方法是实施IEqualityComparer<int[]>
:
class IntArrayEqualityComparer : IEqualityComparer<int[]>
{
public bool Equals(int[] x, int[] y)
{
if (ReferenceEquals(x, y)) return true;
if (ReferenceEquals(null, x)) return false;
if (ReferenceEquals(null, y)) return false;
if (x.Length != y.Length) return false;
for (var i = 0; i < x.Length; i++)
{
if (x[i] != y[i]) return false;
}
return true;
}
public int GetHashCode(int[] x)
{
if (x == null) return 0;
var hashCode = 0;
for (var i = 0; i < x.Length; i++)
{
hashCode = (32 * hashCode) + x[i];
}
return hashCode;
}
}
然后使用重载版本的IEnumerable<TSource>.SequenceEqual
:
private bool sequenceEqual(List<int[]> groupA, List<int[]> groupB)
{
if (ReferenceEquals(groupA, groupB)) return true;
if (ReferenceEquals(null, groupA)) return false;
if (ReferenceEquals(null, groupB)) return false;
return groupA.SequenceEqual(groupB, new IntArrayEqualityComparer());
}
从长远来看,创建一个简单实现Coordinates
的{{1}}类型可能会有所帮助,在这种情况下,您只需比较两个IEquatable<Coordinates>
个对象。