繁体   English   中英

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

[英]How to get the value for complex object from given complex key using c#

我有以下 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 并找到嵌套的结果。 您能否建议如何从给定的复杂键中获取复杂对象的值?

可以像这样通过LINQ完成

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

暂无
暂无

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

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