Linq方法之FirstOrDefault

时间:2024-04-14 13:55:51
List<string> list = new List<string>();
list.Add("a");
list.Add("b");
list.Add("c");



try
{
    var test = list.Where(p => p == "ab").First();
    if (test == null)
    {
        Console.WriteLine("ab is null");
    }
}
catch (Exception ex)
{
    Console.WriteLine("Enter ab and catch an exception " + ex.Message);
}


try
{
    var test = list.Where(p => p == "abc").FirstOrDefault();
    if (test == null)
    {
        Console.WriteLine("abc is null");
    }
}
catch (Exception ex)
{
    Console.WriteLine("Enter abc and catch an exception " + ex.Message);
}

运行截图