c# - 从 C# MVC 中的列表中查找特定值
问题描述
我有这样的项目清单:
selCountry[0] = {IdCountry = 1, LongName = "Austria", CountryUrl = "austria"}
selCountry[1] = {IdCountry = 5, LongName = "Brasil", CountryUrl = "brasil"}
我知道CountryUrl
,我需要找到IDcountry
我尝试了这些方法:
int idCountry;
string country = "brasil";
idCountry = Convert.ToInt32(selCountry.FirstOrDefault(m => m.CountryUrl == country).IdCountry);
idCountry = selCountry.Find(x => x.CountryUrl == country).IdCountry;
idCountry = selCountry.SingleOrDefault(x => x.CountryUrl == country).IdCountry;
每次我得到错误
你调用的对象是空的
如果我调试它,我可以看到类似这样的东西:
System.Linq.Enumerable.SingleOrDefault(...) 返回 null。
我在哪里做错了?
PS:我的问题不是关于如何处理 null 的问题,而是我的代码中的问题在哪里,因为在我的示例中“巴西”存在于列表中,那么,我怎样才能获得 IdCountry?如果我只使用 First 而不是 FirstOrDefault 我得到 System.InvalidOperationException: 'Sequence contains no matching element' 那么怎么可能,没有匹配的元素呢?
我的清单声明
List<CountriesListModel> selCountry = new List<CountriesListModel>();
selCountry = listOfCoutry.CountriesList(24);
我的模型:
public class CountriesListModel
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int IdCountry { get; set; }
[Required]
public string LongName { get; set; }
public string CountryUrl { get; set; }
}
我的调试结果:
https://www.dropbox.com/s/3m8a81ltxn6kiew/listproblem.jpg?dl=0
解决方案
这是解决方案:
selCountry.Where(w=>w.CountryUrl.Equals(country)).select(s=>s.IDcountry)
正如您在上面看到的,您需要使用 .select(s=>s.IDcountry) 因为 Single of Where 的结果是一个看起来像的项目
{IDcountry = 1, LongName = "Austria", CountryUrl = "austria"}
并从中您需要选择 IDcountry 属性。
(如果您确定您将始终拥有国家/地区,则可以使用 Single 而不是 Where 如果没有,您需要检查我们是否有结果并且它不为空,然后选择)
推荐阅读
- angular - 对非 ES5 类调用的 getInternalNameOfClass() 中的错误:预期 TranslateFakeLoader 具有内部类声明
- sql-server - 在 group by 中创建升序 ID
- python - 有没有办法在 python3.7 中管理多个模块版本
- sql - 当一个表有多个对应值时连接两个表
- angular - 角度拖放:如何防止项目被拖放到不需要的列表中
- c++ - 将 enable_shared_from_this 与智能指针一起使用
- pandas - 多索引问题 - 请您更正该问题,因为输出显示为“Nan”
- blazor - Blazor 对象序列化被截断
- css - 如何覆盖一个 ion-popover element.style css
- typescript - 为什么任何条件类型的工作方式不同?