【问题标题】:Using multiple constraints in a JSON query在 JSON 查询中使用多个约束
【发布时间】:2021-08-17 12:20:41
【问题描述】:
using System;
using System.IO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Linq;

namespace ConsoleApp1
{
    public class Program
    {
        public static void Main()
        {
            JObject jObject = JObject.Load(new JsonTextReader(File.OpenText("categories.json")));
            JArray resources = (JArray)jObject["ResourceCategories"];
            foreach (var CategoryType in resources.Where(obj => obj["CategoryID"].Value<string>() == "food") && (obj["GameVersion"].Value<string>() == "1"))
            {
                Console.WriteLine(CategoryType);
            }

            Console.ReadLine();
        }
    }
}

我只能匹配一个条件foreach (var CategoryType in resources.Where(obj =&gt; obj["CategoryID"].Value&lt;string&gt;() == "food")) 当我尝试按照上面的代码添加第二个条件时,我得到一个错误。如何传递多个约束?

【问题讨论】:

  • 当你使用多个约束时会发生什么?什么错误

标签: c# arrays json


【解决方案1】:

我认为你关闭 where 子句太快了。试试下面的代码。为我工作。

foreach (var CategoryType in resources.Where(obj => obj["CategoryID"].Value<string>() == "food" && obj["GameVersion"].Value<string>() == "1"))
        {
            Console.WriteLine(CategoryType);
        }

【讨论】:

  • 谢谢,是一个简单的错字。
【解决方案2】:

您正在关闭where 语句的谓词,并在... == "food" 后面加上括号,因此其他约束不是where 中选择的一部分。

猜测这是一个错误的输入,而您本来打算这样做

foreach (var CategoryType in resources.Where(obj => (obj["CategoryID"].Value<string>() == "food") && (obj["GameVersion"].Value<string>() == "1")))

【讨论】:

    猜你喜欢
    • 2018-06-21
    • 2021-01-26
    • 2011-01-28
    • 2020-06-29
    • 2016-02-23
    • 1970-01-01
    • 2017-04-13
    • 2021-12-15
    • 1970-01-01
    相关资源
    最近更新 更多