我有這樣的項目清單: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
3 回答

九州編程
TA貢獻1785條經驗 獲得超4個贊
這是解決方案:
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 如果沒有,您需要檢查我們是否有結果并且它不為空,然后選擇)

ibeautiful
TA貢獻1993條經驗 獲得超6個贊
System.Linq.Enumerable.SingleOrDefault(...) 返回 null。
固定空值
var ID = selCountry.Where(x => x.IDcountry == 1).Select(s=>s.LongName ).FirstOrDefault();
- 3 回答
- 0 關注
- 233 瀏覽
添加回答
舉報
0/150
提交
取消