亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

從 C# MVC 中的列表中查找特定值

從 C# MVC 中的列表中查找特定值

C#
aluckdog 2022-01-16 14:45:11
我有這樣的項目清單: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 如果沒有,您需要檢查我們是否有結果并且它不為空,然后選擇)


查看完整回答
反對 回復 2022-01-16
?
ibeautiful

TA貢獻1993條經驗 獲得超6個贊

System.Linq.Enumerable.SingleOrDefault(...) 返回 null。
固定空值

 var ID = selCountry.Where(x => x.IDcountry == 1).Select(s=>s.LongName ).FirstOrDefault();



查看完整回答
反對 回復 2022-01-16
?
喵喔喔

TA貢獻1735條經驗 獲得超5個贊

我感謝你們所有人。我是愚蠢的白癡-唯一的問題是-聲明字符串國家-巴西與巴西。真的感謝@NineBery。你拯救了我的夜晚......


查看完整回答
反對 回復 2022-01-16
  • 3 回答
  • 0 關注
  • 233 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號