【问题标题】:How to get the value for complex object from given complex key using c#如何使用c#从给定的复杂键中获取复杂对象的值
【发布时间】:2019-11-26 04:43:10
【问题描述】:

我有以下 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 方法获取值。这是行不通的。 我想我需要拆分密钥并处理复杂的 JSON 并找到嵌套的结果。 您能否建议如何从给定的复杂键中获取复杂对象的值?

【问题讨论】:

  • 试试Dictionary&lt;String,Complex&gt;?

标签: c# json


【解决方案1】:

可以像这样通过LINQ完成

var codeIdToFind = "AU";
var result = data.Where(c => c.Code.ID.Equals(codeIdToFind, StringComparison.OrdinalIgnoreCase))
            .Select(x => x.Country.CountryID)
            .FirstOrDefault();

【讨论】:

  • 您好 HariHaran,感谢您的回答。我的要求是,密钥不能是静态的。它可能有 Code.ID.
  • @PiramaNayagam 然后传递 code.id 而不是 static 字段
  • @PiramaNayagam 我现在根据您的评论更新了我的答案
猜你喜欢
  • 2016-04-30
  • 2019-12-12
  • 2016-05-14
  • 2018-05-25
  • 2021-08-21
  • 1970-01-01
  • 2017-12-27
  • 1970-01-01
  • 2020-05-17
相关资源
最近更新 更多