LINQ Basics
FirstOrDefault
FirstOrDefault finds the first matching value or returns a fallback default.
FirstOrDefault
FirstOrDefaultExample.cs
using System;
using System.Linq;
class Program
{
static void Main()
{
string prefix = ;
string[] codes = { "ax", "by", "bz" };
string match = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";
Console.WriteLine($"prefix={prefix}");
Console.WriteLine($"match={match}");
}
}
using System;
using System.Linq;
class Program
{
static void Main()
{
string prefix = ;
string[] codes = { "ax", "by", "bz" };
string match = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";
Console.WriteLine($"prefix={prefix}");
Console.WriteLine($"match={match}");
}
}
using System;
using System.Linq;
class Program
{
static void Main()
{
string prefix = ;
string[] codes = { "ax", "by", "bz" };
string match = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";
Console.WriteLine($"prefix={prefix}");
Console.WriteLine($"match={match}");
}
}
FirstOrDefault
`FirstOrDefault` returns the first match or a default value when none matches.