Avatar ·

When to use .First() and when .FirstOrDefault() in LINQ in C#?

Hello everyone! I recently started learning C# and LINQ, and I encountered a confusing situation. There are two similar methods: `.First()` and `.FirstOrDefault()`. I understand that both return the first element of a sequence, but what is the difference between them? Let's say I have a list of users: ```csharp List users = new List { "Alice", "Bob", "Charlie" }; ``` If I write: ```csharp string firstUser = users.First(u => u.StartsWith("Z")); ``` then I get an `InvalidOperationException`. But if I use `.FirstOrDefault()`: ```csharp string firstUser = users.FirstOrDefault(u => u.StartsWith("Z")); ``` then there is no exception, and `firstUser` equals `null`. But when is which option more correct to use? I read that `.First()` throws an exception if nothing