C# List Pattern Examples

1 · Phil Haack · Nov. 22, 2022, 5:40 p.m.
We recently upgraded Abbot to .NET 7 and C# 11 and I’m just loving the new language features in C#. In this post, I’ll give a couple examples of list patterns. Single Item List There are cases where I expect up to one item in a list. Any more and I want to throw an exception. Here’s one way you can deal with it: BEFORE List<int> list = SomeMethodThatReturnsAList(someId); var formattedItem = list.SingleOrDefault() is {} singleItem ? $"Formatted: {singleItem}" : "No items found"; Note t...