我想比较请求中的属性是否具有相同的值。我有以下 json 用于通过 PostMan 请求。
“request”:[ {
“Id”: “1234567”,
“Position”: “1”,
“IsSet”: true
},
{
“Id”: “1234587”,
“Position”: “1”,
“IsSet”: true
},
]
在代码中,我想比较属性 Position 和 IsSet 是否对请求中的每个 id 具有相同的值。如果他们不抛出错误。
public class Info
{
public string Id {get; set;}
public string Position {get; set;}
public bool IsSet {get; set;}
}
我有一个名为 Validate 的方法来验证这些属性。
public class Validate(Info context)
{
foreach (var item in context)
{
// what code should check this
}
}
最佳答案
为此,您可以使用 LINQ Select
和 Distinct
。
这是一个示例 “Validate”
方法。
List<Test> objs = new List<Test>()
{
new Test(){ Position = "random position 1", IsSet = true, Id = 123 },
new Test(){ Position = "random position 2", IsSet = true, Id = 123 },
new Test(){ Position = "random position 3", IsSet = true, Id = 123 }
};
if(objs.Count() > 1){
var query = objs.Select(p => new { p.Id, p.IsSet }).Distinct();
var allTheSame = query.Count() == 1;
Console.WriteLine(allTheSame);
}else{
Console.WriteLine("Nothing To Compare Against");
}
}
这里的逻辑是检查列表中是否有超过 1 项 - 只是为了让我们知道有一些值可以与之进行比较。
如果有多个,请选择要匹配对象的属性并对其调用 distinct。
然后我们得到不同值的计数,如果它们都匹配,我们将始终从 query.Count()
返回 1,因此进行 bool 检查。
此时,如果 allTheSame
为 false
,您可以抛出错误而不是 Console.WriteLine
在第二个 Console.WriteLine
中,您始终可以返回 true,因为没有什么可比较的,使其足够独特。
这是一个示例 dotNetFiddle .
关于c# - 比较请求中的属性是否具有相等的值 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55001118/