gpt4 book ai didi

c# - 无法隐式转换类型 'System.Collections.Generic.IEnumerable Cast 错误

转载 作者:行者123 更新时间:2023-11-30 19:15:21 25 4
gpt4 key购买 nike

我有以下模型类。我想根据某些条件从 AddressMatches 列表中检索 AddressMatch 的对象。

public class AddressMatchList
{
public List<AddressMatch> AddressMatches { get; set; }
}

public class AddressMatch
{
public string HouseRange { get; set; }
public string HouseNumber { get; set; }
public string StreetName { get; set; }
public string AddressIdentifier { get; set; }
}

我试过这个:

AddressMatch selectedMatchedAddress = new AddressMatch();   
selectedMatchedAddress = addressMatches.AddressMatches.Where(a => a.AddressIdentifier == "cpr");

但出现错误:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'AddressMatch'. An explicit conversion exists (are you missing a cast?)

最佳答案

Where 返回一个可枚举的(列表)项目,而您期望的只有一个。

如果你想确保只有一个匹配项,你可以使用它(如果找到多个匹配项,SingleOrDefault 将给出一个异常):

selectedMatchedAddress = addressMatches.AddressMatches
.SingleOrDefault(a => a.AddressIdentifier == "cpr");

或者,如果您只想要第一个匹配项:

selectedMatchedAddress = addressMatches.AddressMatches
.FirstOrDefault(a => a.AddressIdentifier == "cpr");

在这两种情况下,检查 selectedMatchedAddress 是否为 null 很重要。

关于c# - 无法隐式转换类型 'System.Collections.Generic.IEnumerable Cast 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40036989/

25 4 0