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

Check values from the list and assign to string in C# asp.net

我有一个 List,其中当前有 13 个(带有名称的 STATE)值。

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

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

如果我传递如下硬编码值,我可以获得它:

UMSLocationDetails[6].LocationName

这给了我 Rajashtan。但是我想要动态的。

可以使用LINQFirstOrDefault(),如下:

var location = UMSLocationDetails.FirstOrDefault(x => x.LocationName == "Rajashtan");
if (location != null)
{
    // do something with location / location.LocationName
}

如果您需要使用找到的项目,上面的答案会更好,但是如果您需要知道它是否存在,请尝试

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

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

var locationName = UMSLocationDetails.FirstOrDefault(x => x.LocationName?.ToLowerInvariant().Trim() == "rajashtan")?.LocationName;

你可以试试这个。

string locationName = UMSLocationDetails.FirstOrDefault(l => l.LocationName == "Rajashtan")?.LocationName;

如果要按索引访问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){}