Fix for Dictionary does not contain a definition for OrderBy C#

This tutorial is a solution for fixing that does not contain a definition for OrderBy and no accessible extension method OrderBy accepting a first argument of type Dictionary.

Using List, Dictionary, and SortedDictionary in C# with LINQ operation OrderBy or OrderByDescending in your code throws an error below error.

Dictionary<int, string> does not contain a definition for OrderBy'and no accessible extension method 'OrderBy' accepting a first argument of type 'Dictionary<int, string>' could be found (are you missing a using directive or an assembly reference?)

or

The type or namespace name 'SortedDictionary<,>' could not be found (are you missing a using directive or an assembly reference?)

OrderBy or OrderByDescending are extension methods in the LINQ package.

Solution for Dictionary does not contain a definition for OrderBy Csharp

Please follow the below steps to fix for OrderBy or OrderByDescending not found.

  • First Make sure that the below libraries are extended in your code
using System;
using System.Linq;

Using System allows you to use System methods and classes.

using System.Linq: Using this, for using LinQ extension methods such as OrderBy etc.

  • Next Step, if the List, Dictionary, and SortedDictionary classes use Generics, You have to use another directive.

For example, Dictionary<string,string> throws an error without using a directive.

using System.Collections.Generic;

Here is an example

using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var numbers = new Dictionary<int, string>
        {
            { 1, "one" },
            { 4, "four" },
            { 2, "two" },
            { 3, "three" },
        };
    }
}