Question

I am trying to get an unique, alphabetized list of industry names (strings). Here is my code:

HashSet<string> industryHash = new HashSet<string>();
List<string> industryList = new List<string>();
List<string> orderedIndustries = new List<string>();

// add a few items to industryHash

industryList = industryHash.ToList<string>();
orderedIndustries = industryList.Sort(); //throws compilation error

The last line throws a compilation error: "Cannot implicitly convert type 'void' to 'System.Collections.Generic.List"

What am I doing wrong?

Was it helpful?

Solution

List.Sort sorts the original list and does not return a new one. So either use this method or Enumerable.OrderBy + ToList:

efficient:

industryList.Sort();

less efficient:

industryList = industryList.OrderBy(s => s).ToList();

OTHER TIPS

Sort is a void method, you can't retrieve a value from this method. You can look on this article

You can use OrderBy() to order your list

It sorts the list in-place. If you want a copy, use OrderBy.

Do this :

HashSet<string> industryHash = new HashSet<string>();
List<string> industryList = new List<string>();

// add a few items to industryHash

industryList = industryHash.ToList<string>();
List<string> orderedIndustries = new List<string>(industryList.Sort()); 

Note : that don't keep the unsorted list, so no real point over doing just industryList.Sort()

One option is using LINQ and removing industryList:

HashSet<string> industryHash = new HashSet<string>();
//List<string> industryList = new List<string>();
List<string> orderedIndustries = new List<string>();

orderedIndustries = (from s in industryHash
                     orderby s
                     select s).ToList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top