首页 > 解决方案 > 从 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

标签: c#linq

解决方案


这是解决方案:

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 如果没有,您需要检查我们是否有结果并且它不为空,然后选择)


推荐阅读