如果找到则获取字符串”;字符串“;在列表中

本文关键字:字符串 列表 获取 如果 | 更新日期: 2023-09-27 18:28:16

我想获得完整的字符串如果我在列表中创建字符

我的代码:

List<string> mylist = new List<string>(); 
// My List Contains : 1-Cat , 2-Dog , 3-Wolf , 4-Mouse
string text = "";
if (mylist.contains("3")) 
{
    text = ...//Get The Line That The "3" Is Founded In It
    // In This Case text must be : 3-Wolf
}

谢谢,

如果找到则获取字符串”;字符串“;在列表中

您可以使用此代码

var text = mylist.FirstOrDefault(x => x.Contains("3"));
// note: text will be **null** if not found in the list

应该由以下人员提供服务:

        List<string> mylist = new List<string>() { "1-Cat", "2-Dog", "3-Wolf", "4-Mouse" };
        // My List Contains : 1-Cat , 2-Dog , 3-Wolf , 4-Mouse
        string text = "";
        text = mylist.FirstOrDefault(x => x.Contains('3')); // text will be 3-Wolf. In case there is no strings in the list that contains 3 text will be null.
        // If you want do some other things if the list contains "3" you can do the following:
        if (!string.IsNullOrEmpty(text))
        {
            // Do your stuff here
        }