如何使用c#从给定的复杂键中获取复杂对象的值

问题描述 投票:0回答:1

我有以下JSON。

public class Code
{
  public string ID { get; set; }
}

public class Country
{
  public string CountryID { get; set; }
}

public class Complex
{
  public Country Country { get; set; }
  public Code Code { get; set; }
  public string cText { get; set; }
}

public List<Complex> GetData()
{
  List<Complex> Data = new List<Complex>();
  Data.Add(new Complex() { Country = new Country() { CountryID = "Australia" }, Code = new Code() { ID = "AU" }, cText = "Australia" });
  Data.Add(new Complex() { Country = new Country() { CountryID = "Bermuda" }, Code = new Code() { ID = "BM" }, cText = "Bermuda" });
  Data.Add(new Complex() { Country = new Country() { CountryID = "Canada" }, Code = new Code() { ID = "CA" }, cText = "Canada" });
  Data.Add(new Complex() { Country = new Country() { CountryID = "France" }, Code = new Code() { ID = "FR" }, cText = "France" });
  return Data;
}

我需要从给定的复杂键(“ Country.CountryID”)中获取CountryID的值。我尝试使用c#中的TryGetValue方法获取值。这是行不通的。我想我需要拆分键并处理Complex JSON并找到嵌套结果。您能否建议如何从给定的复杂键中获取复杂对象的值?

c# json blazor blazor-server-side
1个回答
0
投票

可以通过LINQ这样完成

var result = data.Find(d => d.Country.CountryID.Equals("Australia", StringComparison.OrdinalIgnoreCase)).Country.CountryID;

工作解决方案:Dotnetfiddle

© www.soinside.com 2019 - 2024. All rights reserved.