gpt4 book ai didi

c# - 如何检查两个对象的属性是否相等

转载 作者:太空宇宙 更新时间:2023-11-03 23:02:03 26 4
gpt4 key购买 nike

我有两个使用 ff 的对象。类:

public class Test {
public string Name {get; set;}
public List<Input> Inputs {get;set;}
......
//some other properties I don't need to check
}

public class Input {
public int VariableA {get;set;}
public int VariableB {get;set;}
public List<Sancti> Sancts {get;set;}
}

public class Sancti {
public string Symbol {get;set;}
public double Percentage {get;set;}
}

我想检查 Test 的两个实例是否具有相同的 Inputs 值。我已经使用循环完成了此操作,但我认为这不是执行此操作的方法。

我已经阅读了一些链接:link1 , link2但它们对我来说似乎是胡言乱语。有没有更简单的方法来做到这一点,比如像这样的单行:

test1.Inputs.IsTheSameAs(test2.Inputs)?

我真的希望有一个更具可读性的方法。最好是 Linq

注意:输入顺序无关紧要。

最佳答案

您可以更改您的 InputSancti 类定义以覆盖 EqualsGetHasCode。以下解决方案在以下情况下认为 2 个输入相等:

  1. VariableA 相等且
  2. VariableB 相等且
  3. Sancts 列表是相等的,考虑到具有相同 SymbolSancti 元素必须具有相同的 Percentage 平等

如果您的规范不同,您可能需要更改此设置:

public class Input
{
public int VariableA { get; set; }
public int VariableB { get; set; }
public List<Sancti> Sancts { get; set; }

public override bool Equals(object obj)
{
Input otherInput = obj as Input;
if (ReferenceEquals(otherInput, null))
return false;
if ((this.VariableA == otherInput.VariableA) &&
(this.VariableB == otherInput.VariableB) &&
this.Sancts.OrderBy(x=>x.Symbol).SequenceEqual(otherInput.Sancts.OrderBy(x => x.Symbol)))
return true;
else
{
return false;
}

}
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + VariableA.GetHashCode();
hash = hash * 23 + VariableB.GetHashCode();
hash = hash * 23 + Sancts.GetHashCode();
return hash;
}
}
}

public class Sancti
{
public string Symbol { get; set; }
public double Percentage { get; set; }

public override bool Equals(object obj)
{
Sancti otherInput = obj as Sancti;
if (ReferenceEquals(otherInput, null))
return false;
if ((this.Symbol == otherInput.Symbol) && (this.Percentage == otherInput.Percentage) )
return true;
else
{
return false;
}
}

public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hash = 17;
// Suitable nullity checks etc, of course :)
hash = hash * 23 + Symbol.GetHashCode();
hash = hash * 23 + Percentage.GetHashCode();
return hash;
}
}
}

执行此操作,您只需执行此操作以检查 Input 是否相等:

test1.Inputs.SequenceEqual(test2.Inputs);

关于c# - 如何检查两个对象的属性是否相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42768371/

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