简体   繁体   English

比较字符串和数组

[英]Compare string to array

I want to compare a string (postcode, eg:"50000") to array of string elements and if the array contain the postcode stated, it need to select the "PSHid" of the array.我想将字符串(邮政编码,例如:“50000”)与字符串元素数组进行比较,如果数组包含规定的邮政编码,则需要 select 数组的“PSHid”。 I managed to deserialized the Json file but not I'm stuck how to compare my postcodes.我设法反序列化了 Json 文件,但我不知道如何比较我的邮政编码。 Here is my code:这是我的代码:

using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Net.Http;

namespace ConsoleApp1
{

    public class Program
    {
        static async Task Main(string[] args)
        {
            string url = "https://raw.githubusercontent.com/kayh1105/msiaPostcodes/main/ShortList_MsiaCitiesPostcodes";
            HttpClient httpClient = new HttpClient();

            var httpResponseMessage = await httpClient.GetAsync(url);
            string jsonResponse = await httpResponseMessage.Content.ReadAsStringAsync();
            Console.WriteLine(jsonResponse);
            var data = JsonConvert.DeserializeObject<MsiaPostcode>(jsonResponse);            
        }
    }
}

public class MsiaPostcode
{
    public _State[] state { get; set; }
}

public class _State
{
    public string name { get; set; }
    public _City[] city { get; set; }
}

public class _City
{
    public string name { get; set; }
    public int PSHid { get; set; }
    public string[] postcode { get; set; }
}

and below is my Json sample:下面是我的 Json 示例:

{
  "state": [
    {
      "name": "Wp Kuala Lumpur",
      "city": [
        {
          "name": "Kuala Lumpur",
          "PSHid": 1,
          "postcode": [
            "50000",
            "50050"
          ]
        },
        {
          "name": "Setapak",
          "PSHid": 2,
          "postcode": [
            "53300"
          ]
        }
      ]
    },
    {
      "name": "Johor",
      "city": [
        {
          "name": "Ayer Baloi",
          "PSHid": 3,
          "postcode": [
            "82100"
          ]
        },
        {
          "name": "Ayer Hitam",
          "PSHid": 4,
          "postcode": [
            "86100"
          ]
        },
        {
          "name": "Yong Peng",
          "PSHid": 5,
          "postcode": [
            "83700",
            "83710"
          ]
        }
      ]
    }
  ]
}

You can do a simple LINQ query like so, it'll select the cities first, then query them to get only the set where a postcode matches your input, "50000" in this case, then select the PSHid , and then finally return it as a list.您可以像这样执行一个简单的 LINQ 查询,它将首先查询城市 select,然后查询它们以仅获取邮政编码与您的输入匹配的集合,在本例中为“50000”,然后是 select PSHid ,最后返回它作为列表。

data.state
    .SelectMany(x => x.city)
    .Where(x => x.postcode.Any(y => y == "50000")))
    .Select(x => x.PSHid)
    .ToList();

First flatten the list of states ( many to many relationship : Many states, each state can have multiple cities) into list of cities.首先将州列表(多对多关系:许多州,每个 state 可以有多个城市)扁平化为城市列表。

After getting list of cities filter by Postcode,在获得按邮政编码过滤的城市列表后,

To Flatten the list of list into one sequential list将列表列表展平为一个顺序列表

SelectMany(): Projects each element of a sequence to an IEnumerable and flattens the resulting sequences into one sequence. SelectMany():将序列的每个元素投影到 IEnumerable 并将结果序列展平为一个序列。

var PSHids = data.state
    .SelectMany(x => x.city) //Convert list of states into list of cities
    .Where(x => x.postcode.Contains("50000")))  //Filter by postcode
    .Select(x => x.PSHid) //Select PSHid property only
    .ToList();   //Convert IEnumerable<int> to List<int>

to find PSHid you don't need any custom classes at all, parse the json and use Linq要查找 PSHid,您根本不需要任何自定义类,解析 json 并使用 Linq

   string postCode = "50000";

    int PSHid = JObject.Parse(jsonResponse)["state"]
        .SelectMany(x => x["city"])
        .Where(x => ((JArray)x["postcode"]).ToArray().Contains(postCode))
        .Select(x => (int)x["PSHid"])
        .FirstOrDefault(); //  1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM