比较来自世界各地的卖家的域名和 IT 服务价格

列表的比较 价值 C#

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




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


我必须每次添加唯一的坐标,这意味着下一次 x_axis, y_axis 如果它相等,永远不会添加到列表中 200, 300 分别。

如何检查列表对象中已存在的元素?


</object>
已邀请:

诸葛浮云

赞同来自:

相反,使用
List<coordinates>

.

要检查坐标设置是否在列表中,必须通过列表执行循环并比较属性值:


Coordinates point = new Coordinates/200, 300/;

if /!container.Any/c =&gt; c.x_axis == point.x_axis &amp;&amp; c.y_axis = point.y_axis// {
container.Add/point/;
}


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


并使用一般列表或 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//;


</coordinates></coordinates></coordinates></coordinates>

喜特乐

赞同来自:

您可以将从容器中拉出的物品带回坐标,然后检查它们的值。 x 和 y. 或者如果他继承了 ICombparable, 只需使用操作员=。
如果不是 IComparable, 您可以创建自己的类并继承界面。 IComerable.


var myCoord = /Coordinates/ container/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//;

卫东

赞同来自:

你最好使用
http://msdn.microsoft.com/en-u ... .aspx
或者
http://msdn.microsoft.com/en-u ... .aspx
/如果您需要以某个订单保留它们/, 确保他们真的是独一无二的。

然后你必须覆盖
http://msdn.microsoft.com/en-u ... .aspx

http://msdn.microsoft.com/en-u ... .aspx
, 检查平等。

最好的做法 GetHashCode:
https://coderoad.ru/263400/
销售量


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 =&gt; p.Value/.Select/p =&gt; p.Key/;


HashSet


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


</coordinate></coordinate></coordinate,></coordinate,>

要回复问题请先登录注册