c# - 比较请求中的属性是否具有相等的值 C#

标签 c# dotnet-httpclient

我想比较请求中的属性是否具有相同的值。我有以下 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 SelectDistinct

这是一个示例 “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 检查。

此时,如果 allTheSamefalse,您可以抛出错误而不是 Console.WriteLine

在第二个 Console.WriteLine 中,您始终可以返回 true,因为没有什么可比较的,使其足够独特。

这是一个示例 dotNetFiddle .

关于c# - 比较请求中的属性是否具有相等的值 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55001118/

相关文章:

c# - SortedDictionary 是否自动排序?

c# - HttpClient 和 ASP.NET Core 2.0 web 服务之间的连接已关闭错误

c# - Polly 记录所有带有 URL、 header 、内容和响应的请求

C# 和泛型 : how can I handle processing based on type?

c# - 找到树的最大深度

c# - C# 中的重载运算符实际上是好的做法吗?

c# - 过滤 GroupJoin 查询

c# - 决定哪些属性在运行时被序列化

c# - HttpClient.发送异步 HttpException : The Client Disconnected

unit-testing - 在 VS 2013 中使用 HttpClient 代理类对 Web API 进行单元测试