如果对象列表中不存在对象字段,则更新它?

我有 2 个如下所示的对象列表:


public class Object1

{

    public string Value1 {get; set;}

    public string Value2 {get; set;}

    public bool Exclude {get; set;}

}

第二个包含我想用来从第一个对象中排除值的值。


public class Object2

{

    public string Value1 {get; set;}

    public string Value2 {get; set;}


}

如果 Value1 和 Value2 不同时匹配 Object2 中的两个属性,我该如何编写将 Exclude 的值设置为 true 的内容?


List<Object1> object1 = new List<Object1>();

List<Object2> object2 = new List<Object2>();


繁花不似锦
浏览 145回答 3
3回答

手掌心

您可以尝试以下方法:if(!listOfObject2.Any(x => x.Value1 == object1.Value1&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; && x.Value2 == object1.Value2)){&nbsp; &nbsp; object1.Exclude = true;}在上面的代码片段中,listOfObject2是 typeList<Object2>和object1type Object1。

Smart猫小萌

Object1另一种方法是在类上实现一个比较方法,如果属性匹配则接收Object2并返回:truepublic class Object1{&nbsp; &nbsp; public string Value1 { get; set; }&nbsp; &nbsp; public string Value2 { get; set; }&nbsp; &nbsp; public bool Exclude { get; set; }&nbsp; &nbsp; public bool ValuesMatch(Object2 other)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; return (other != null) &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Value1 == other.Value1 &&&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Value2 == other.Value2;&nbsp; &nbsp; }}然后你可以在你的 Linq 语句中使用这个方法:object1.ForEach(o1 => o1.Exclude = object2.Any(o1.ValuesMatch));

跃然一笑

如果您有两个列表,则应该可以:foreach (var obj1 in object1){&nbsp; &nbsp; obj1.Exclude = true;&nbsp; &nbsp; foreach (var obj2 in object2)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (obj1.Value1.Equals(obj2.Value1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || obj1.Value1.Equals(obj2.Value2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || obj1.Value2.Equals(obj2.Value1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || obj1.Value2.Equals(obj2.Value2))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; obj1.Exclude = false;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}这将初始化Exclude为 true,然后循环遍历Object1列表并将其两个值Object2与 object2 列表中的每个值进行比较。如果找到匹配项,则将 exclude 设置为 false 并中断内部循环,因为它不再需要查看。如果它一直通过,Exclude保持真实。
打开App,查看更多内容
随时随地看视频慕课网APP