代码之家  ›  专栏  ›  技术社区  ›  hud

检查列表中的值并将其分配给C#asp.net中的字符串

  •  0
  • hud  · 技术社区  · 5 年前

    List 其中当前有13个(带名称的状态)值。

    List<UMSLocationDetails> UMSLocationDetails = (List<UMSLocationDetails>)Session["lstUMSLocationDetails"];
    

    所以我想检查一下是否在这个列表中 Rajashtan 有没有。如果存在,我想将其分配给 string 变量

    UMSLocationDetails[6].LocationName
    

    这让我 拉贾斯坦邦

    4 回复  |  直到 5 年前
        1
  •  1
  •   Peter B    5 年前

    您可以使用LINQ FirstOrDefault()

    var location = UMSLocationDetails.FirstOrDefault(x => x.LocationName == "Rajashtan");
    if (location != null)
    {
        // do something with location / location.LocationName
    }
    
        2
  •  0
  •   Neal    5 年前

    var locationExists = UMSLocationDetails.Any(x => x.LocationName.ToLowerInvariant() == "rajashtan");
    

    有了新的C#和它的空合并,参考现有的答案,生活变得更加轻松:

    var locationName = UMSLocationDetails.FirstOrDefault(x => x.LocationName?.ToLowerInvariant().Trim() == "rajashtan")?.LocationName;
    
        3
  •  0
  •   Serkan Arslan    5 年前

    你可以试试这个。

    string locationName = UMSLocationDetails.FirstOrDefault(l => l.LocationName == "Rajashtan")?.LocationName;
    
        4
  •  0
  •   cdev    5 年前

    FindIndex

        string state = "Rajashtan";
        int index = UMSLocationDetails.FindIndex(c => c.LocationName == state);
        if (index >= 0) 
        string locationName = UMSLocationDetails[index].LocationName;
    

    如果你想找到唯一的存在,然后做其他事情

        string state = "Rajashtan";
        bool exists = UMSLocationDetails.Any(c => c.LocationName == state);
        if (exists){}