C# – Read a text file line by line

There are two simple ways to read a text file line by line: Here’s an example of using File.ReadLines() to read a file line by line in a loop: This outputs the file’s lines: Here’s an example of using File.ReadAllLines() to read the same file into a string array and then loop through it. Skip … Read more

C# – Remove duplicates from a list

The simplest (and most efficient) way to remove duplicates from a list is by iterating, keeping track of items you’ve seen with a HashSet, and discarding items you’ve already seen. I’ll show four ways to implement this O(n) algorithm. At the end, I’ll explain a few inefficient approaches to avoid. Remove duplicates with ToHashSet() and … Read more

C# – Convert string list to int list

You can convert a list of strings to a list of integers by using int.Parse() on all of the strings. There are two simple ways to do this: I’ll show examples of these using these methods and then explain how to handle parsing exceptions. Option 1 – Use List.ConvertAll() Here’s an example of how to … Read more

C# – Convert an array to a list

The simplest way to convert an array to a list is with the ToList() Linq method: This outputs the following: The List<T> class stores data in a dynamically sized array. So converting an array to a list boils down to copying the array to the list’s internal array. That’s what ToList() does. It creates a … Read more

C# – How to sort a list

When you need to sort a list, you don’t need to reinvent the wheel. You can use one of these three built-in methods for sorting a list: In this article, I’ll show examples of using these three approaches for sorting a list. Sort a list with OrderBy() (Linq) The OrderBy() Linq method generates an IOrderedEnumerable … Read more

C# – How to parse XML with XElement (Linq)

Use the XElement class (from the Linq-to-Xml API) to parse XML and work with it in memory. You can use this to search for XML elements, attributes, and modify values. This is an alternative to deserializing to an object (which requires you to define a class that matches the XML structure). I’ll show examples of … Read more

C# – Read XML element attributes with XElement (Linq)

XML elements can have attributes, which are key-value pairs. To read the attributes, use the XElement class (from the Linq-to-Xml API). There are two main methods for getting attributes: Once you have the attributes, use the XAttribute.Value property to read the attribute’s string value. Here’s an example of getting all elements named Movie and then … Read more

C# – Examples of using GroupBy() (Linq)

Here’s an example of using the Linq GroupBy() method to group coders by language: This example outputs the following: GroupBy() produces groups that contain the grouping key (i.e. Language) and the list of objects in the group (i.e. the Coder objects). The GroupBy() syntax is complex because it supports many scenarios. You can select one … Read more

C# – Select distinct objects based on a property with Linq

There are three ways to select distinct objects based on a property using Linq methods: These select one movie per year: GroupBy() is the simplest because it doesn’t require any additional code. Distinct() is faster but it’s more complicated. DistinctBy() is the fastest and simplest, but requires the most code (it requires .NET 6 or … Read more

C# – Set operations with Linq

You can use Linq methods to do set operations (intersection, union, difference, and symmetric difference). These work on any type that implements IEnumerable – such as lists, arrays, and sets. I’ll explain these set operations and show how to do them with Linq methods. Set intersection with Intersect() The intersection of set A {1,2} and … Read more

C# – Sort all but first element (Linq)

To sort a list, except for the first element, you need to: This can be accomplished in a single line using Linq methods: Example – sorting a list of people Let’s say we have a list of people, such as the following: Here’s how to sort the people by first name, except for the first … Read more

C# – How to sort by multiple fields (Linq)

Use the OrderBy() and ThenBy() Linq methods when you want to sort by multiple fields, like this: 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 each method. For example, if I want to sort NFL teams within … Read more

Error: 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

Could not find an implementation of the query pattern for source type

Problem Any time you try to use a Linq extension method (such as Select() to transform list elements) and you haven’t added ‘using System.Linq’, you’ll get a compiler error like this: Could not find an implementation of the query pattern for source type ‘Your Type’.  ‘Select’ not found. In newer versions, the error looks like … Read more