寻找相同的对象名称,然后比较结构 [英] Looking for the same objectname and then compare the structure

查看:59
本文介绍了寻找相同的对象名称,然后比较结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我想:

用对象填充列表

如果object.name出现多次

然后

比较两者的结构

如果两个结构都相同

显示消息框(或其他内容)

其他

什么都不做


简单比较有什么问题,例如:

Hi there

I wanted to:

fill a list with objects

if a objects.name occurs more than once

then

compare the structure of the two

if the both structures are the same

show messagebox (or just something)

else

do nothing


Whats wrong with simply comparison like:

if (oObjList.Contains(oObj))





我已经提前感谢了





i thank already in advance

推荐答案

我假设我们正在使用列表< T> ;.包含方法 [ ^ ]和IEquatable<T> ;.等于方法 [
I am assuming that we are using List <T>[^] to implement your list of objects.

If you read the documentation of the List<T>.Contains Method[^] and IEquatable<T>.Equals Method[^] you will see that your statement will work if all the objects stored in the list implement the IEquatable interface.

Define the Equals function in the objects like:
public override bool Equals(Object obj)


通过此实现,当对象属于不同类型时,您可以返回false,请参见接口文档中的示例.


with this implementation you can return false when the objects are of different types, see the sample in the interface documentation.


您是否控制对象属于实例的类?如果是这样,您可以覆盖Equals和==,以便a == b返回您想要的内容.例如一个简单的例子
Do you control the class of which the objects are instances? If so, you can override Equals and == so that a == b returns what you want. E.g, a trivial example
class Test {
 int a; double b;

 public static operator bool == (Test a, Test b) { return (object)a == null ? (object)b == null : a.Equals(b); }
 public static operator bool != (Test a, Test b) { return !(a == null); }

 public override bool Equals(object o){
  if(o is Test){
   Test test = (Test)o;
   return a == test.a && b == test.b;
  } else return base.Equals(o);
 }

 public override int GetHashCode(){ return a.GetHashCode() ^ b.GetHashCode(); }
}



如果不是,并且您事先不知道对象是什么类型,则需要使用反射,对它们的字段/属性/等进行排序(无论您算作结构"如何)并进行比较.



If not, and you don''t know in advance what type the objects will be, you''ll need to use reflection, make a sorted list of their fields/properties/etc (whatever you count as ''structure'') and compare those.


现在这是我的解决方案(关键字LINQ):

Now here''s my solution (keyword LINQ):

public void AddType(PvssType dpt)
{
    if (this.Any(tp => tp.n.Name == dpt.n.Name))return;

    this.Add(dpt);
}


这篇关于寻找相同的对象名称,然后比较结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆