C# – Merge two dictionaries in-place

When you merge two dictionaries, you can either merge them in-place, or create a new dictionary and copy the values over to it. The following extension method does an in-place merge of two dictionaries. It puts items from the right dictionary into the left dictionary. When duplicate keys exist, it’s keeping the value from the … Read more C# – Merge two dictionaries in-place

C# – How to sort by multiple fields

Use OrderBy() and ThenBy() when you want to sort by multiple fields, like this: Note: These are Linq extension methods, so make sure to add a reference to System.Linq. Ascending vs Descending order By default, OrderBy() and ThenBy() sort in ascending order. If you want to sort by descending order, use the Descending version of … Read more C# – How to sort by multiple fields

System.InvalidOperationException: Sequence contains no elements

Problem When you call .First() on an empty IEnumerable, you get the following exception: System.InvalidOperationException: Sequence contains no elements Solution Option 1 – Use .FirstOrDefault() instead of .First() When the IEnumerable is empty, .FirstOrDefault() returns the default value for the type. For reference types this returns null. For value types this returns 0 or that … Read more System.InvalidOperationException: Sequence contains no elements