C#创建两个iLists之间的关系

本文关键字:iLists 之间 关系 两个 创建 | 更新日期: 2023-09-27 18:29:17

我正试图将一个名称从一个iList中提取到另一个iList中,它们都包含相同的ID。

    public class Notifications 
{
    [JsonProperty("note_id")]
   public int note_id { get; set;}
    [JsonProperty("sender_id")]
    public int sender_id { get; set;}
    public string sender_name { get; set; }
    [JsonProperty("receiver_id")]
    public int receiver_id { get; set; }
    [JsonProperty("document_id")]
    public int document_id { get; set; }
    [JsonProperty("search_name")]
    public string search_name { get; set; }
    [JsonProperty("unread")]
    public int unread { get; set; }
}
public class CompanyDirectory
{
    [JsonProperty("contact_id")]
    public int contact_id { get; set; }
    [JsonProperty("first_name")]
    public string first_name { get; set; }
    [JsonProperty("second_name")]
    public string second_name { get; set; }
    [JsonProperty("extension")]
    public string extension { get; set; }
    [JsonProperty("direct_dial")]
    public string direct_dial { get; set; }
    [JsonProperty("job_title")]
    public string job_title { get; set; }
    [JsonProperty("company_id")]
    public int company_id { get; set; }
}

然后我做以下操作,这两个列表都填充得很好。奇怪的是,我在做CompanyDir.first_name时出错,说该属性不存在,它显然存在?:

// This occurs just after the class declaration
public IList<Notifications> Notes;
public IList<CompanyDirectory> CompanyDir;
// Ignore that these both use the same string they're created at different parts of the load process
CompanyDir = JsonConvert.DeserializeObject<IList<CompanyDirectory>>(responseString);
Notes = JsonConvert.DeserializeObject<IList<Notifications>>(responseString);
// Now I thought I should be able to do
foreach(var s in Notes){
  var thename = CompanyDir.first_name.Where(contact_id.Contains(s.sender_id))
}

C#创建两个iLists之间的关系

您应该查找LinQ和Lambda表达式:

var firstNames = CompanyDir.Where(c => c.contact_id == s.sender_id)
                           .Select(c => c.first_name)
                           .ToList();

现在你有了一个名字列表。一个列表,因为您的Where约束可能有零个或多个命中。