LINQ Basics
FirstOrDefault
FirstOrDefault finds the first matching value or returns a fallback default.
FirstOrDefault
`FirstOrDefault` returns the first match or a default value when none matches.
FirstOrDefault
FirstOrDefaultExample.cs
Replay: real traced execution (multi-file project)
using System;
using System.Linq;
class Program
{
static void Main()
{
string prefix = "b";
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 = "a";
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 = "z";
string[] codes = { "ax", "by", "bz" };
string match = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";
Console.WriteLine($"prefix={prefix}");
Console.WriteLine($"match={match}");
}
}
prefix ← b, match ← by
5{6 static void Main()7 {8 string prefix→ b = "b"; //@prefix="a", "z"9 string[] codes = { "ax", "by", "bz" };10 string match→ by = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";1112 Console.WriteLine($"prefix={prefixb}");13 Console.WriteLine($"match={matchby}");14 }outputprefix=b match=by
prefix ← a, match ← ax
5{6 static void Main()7 {8 string prefix→ a = "a";9 string[] codes = { "ax", "by", "bz" };10 string match→ ax = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";1112 Console.WriteLine($"prefix={prefixa}");13 Console.WriteLine($"match={matchax}");14 }outputprefix=a match=ax
prefix ← z, match ← none
5{6 static void Main()7 {8 string prefix→ z = "z";9 string[] codes = { "ax", "by", "bz" };10 string match→ none = codes.FirstOrDefault(code => code.StartsWith(prefix)) ?? "none";1112 Console.WriteLine($"prefix={prefixz}");13 Console.WriteLine($"match={matchnone}");14 }outputprefix=z match=none