C# – Find duplicate values in a dictionary

Dictionaries contain key/value pairs. The keys must be unique, but the values can be repeated many times. When you want to find duplicate values, the simplest option is to use Linq methods GroupBy() and Where(), like this: Note: I initialized the dictionary with a few duplicate values. This groups the dictionary key/value pairs by value. … 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# – Convert a list to a dictionary

The simplest way to convert a list to a dictionary is to use the Linq ToDictionary() method: This loops through the list and uses the key/element selector lambdas you passed in to build the dictionary. In this article, I’ll go into details about how to use ToDictionary() and show how to deal with duplicate keys. … Read more

C# – Unit testing code that does File IO

If your code does File IO, such as reading text from a file, then it’s dependent on the file system. This is an external dependency. In order to make the unit tests fast and reliable, you can mock out the external dependencies. To mock out the file system dependency, you can wrap the File IO … 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: The simplest option is using GroupBy() 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 … Read more