C#: List does not contain a definition for 'OrderBy'

Date: 2019-02-04 | csharp | list | tutorial | troubleshoot |

Problem

I'm writing a C# script but am running into the exception:

error CS1061: Type `System.Collections.Generic.List<int>' does not contain a definition for `OrderBy' and no extension method `OrderBy' of type `System.Collections.Generic.List<int>' could be found.

I tried to use OrderByDescending instead but am getting a very similar result. What's happening? I know that List has an OrderBy function on it, so why can't I use it?

Solution

The issue is likely that the IDE you're used to developing in is better at guessing what imports you need than the one you're currently using for this. To use the OrderBy or OrderByDescending methods, you will need to import a few built-in libraries using the using directive as so:

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

Because your error was being triggered by the lack of a known List extension method and not by the usage of a generic list itself, my guess is that the using statement you really need is just using System.Linq but it's probably a good idea to make sure you have all of those either way.

Happy coding!

-HAMY.OUT

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.