比较List <object>值C#</object>

时间:2012-04-16 08:08:01

标签: c# list object compare

我遇到列表对象值的问题。 Object是一个包含两个整数的类的对象。

喜欢

List<Object> container;
container.Add(new Coordinates(x_axis, y_axis));  // x_axis=200, y_axis=300

我每次都要添加唯一的坐标,意味着下次x_axis,y_axis永远不会被添加到列表中,如果它分别是200,300。

如何检查列表对象中已存在的项目?

由于

5 个答案:

答案 0 :(得分:3)

改为使用List<Coordinates>

要检查列表中是否存在一组坐标,您必须遍历列表并比较属性值:

Coordinates point = new Coordinates(200, 300);

if (!container.Any(c => c.x_axis == point.x_axis && c.y_axis = point.y_axis)) {
  container.Add(point);
}

答案 1 :(得分:3)

覆盖Coordinates类的Equals和GetHashCode:

public class Coordinates
{
    public Coordinates(int x, int y)
    {
        X = x;
        Y = y;
    }

    public int X { get; private set; }
    public int Y { get; private set; }

    public override bool Equals(object obj)
    {
        if (!(obj is Coordinates))
        {
            return false;
        }
        Coordinates coordinates = (Coordinates)obj;
        return ((coordinates.X == this.X) && (coordinates.Y == this.Y));
    }

    public override int GetHashCode()
    {
        return (X ^ Y);
    }
}

使用Coordinates对象的通用List或HashSet:

List<Coordinates> container = new List<Coordinates>();
Coordinates coordinates = new Coordinates(x_axis, y_axis);

if (!container.Contains(coordinates)
    container.Add(coordinates);

使用HashSet:

HashSet<Coordinates> container = new HashSet<Coordinates>();
container.Add(new Coordinates(x_axis, y_axis));

答案 2 :(得分:0)

您可以将从容器中拉出的项目转换回坐标,然后检查它们的x和y值。或者如果它继承自ICombparable,只需使用=运算符即可。 如果它不是IComparable,你可以创建自己的类,并继承IComerable接口。

    var myCoord = (Coordinates) container(0);

这就是假设你真的不想让你的容器直接拿着坐标。

编辑:修正了一堆拼写错误

答案 3 :(得分:0)

您可以像这样使用LINQ:

if (!container.Any(c => (Coordinates)c.x_axis == x_axis &&
                        (Coordinates)c.y_axis == y_axis))
    container.Add(new Coordinates(x_axis, y_axis));

答案 4 :(得分:0)

您最好使用HashSetDictionary(如果您需要按特定顺序保留它们),以确保它们真的是唯一的。

然后你应该覆盖GetHashCodeEquals来检查相等性。

GetHashCode的最佳做法:What is the best algorithm for an overridden System.Object.GetHashCode?

实施

public class Coordinate
{
    public Int32 X { get; set; }
    public Int32 Y { get; set; }

    public override int GetHashCode()
    {
        Int32 hash = 17;
        hash = hash * 23 + X;
        hash = hash * 23 + Y;
        return hash;
    }
    public override Boolean Equals(object obj)
    {
        Coordinate other = obj as Coordinate;
        if (other != null)
        {
            return (other.X == X) && (other.Y == Y);
        }
        return false;
    }
}

词典

Int32 count = 0;
Dictionary<Coordinate, Int32> cords = new Dictionary<Coordinate, Int32>();
// TODO : You need to check if the coordinate exists before adding it
cords.Add(new Coordinate() { X = 10, Y = 20 }, count++);
// To get the coordinates in the right order
var sortedOutput = cords.OrderBy(p => p.Value).Select(p => p.Key);

HashSet的

HashSet<Coordinate> cords = new HashSet<Coordinate>();
cords.Add(new Coordinate() { X = 10, Y = 20 });