Problem with List<>.Sort()

  • Thread starter Thread starter pinkfloydfan
  • Start date Start date
P

pinkfloydfan

Hi there

In a Form I have created I am trying to Sort a List<string> extracted
from the Keys of a Dictionary. However, when I attempt to build the
project I get the following error:

Cannot implicitly convert type 'void' to 'object'

The relevant code is as follows:

private void Form1_Load(object sender, EventArgs e)
{
List<string> Keys1 = new
List<string>(Class1.Dictionary1.Keys);
this.listbox1.DataSource = Keys1.Sort();
}

Without the Sort it works fine but the Keys are obviously not sorted.

Can anyone help me to fix this please?

Many Thanks
Lloyd
 
pinkfloydfan said:
In a Form I have created I am trying to Sort a List<string> extracted
from the Keys of a Dictionary. However, when I attempt to build the
project I get the following error:

Cannot implicitly convert type 'void' to 'object'

The relevant code is as follows:

private void Form1_Load(object sender, EventArgs e)
{
List<string> Keys1 = new
List<string>(Class1.Dictionary1.Keys);
this.listbox1.DataSource = Keys1.Sort();
}

Without the Sort it works fine but the Keys are obviously not sorted.

Can anyone help me to fix this please?

Sort sorts the list in place, and returns void:

List<string> Keys1 = new List<string>(Class1.Dictionary1.Keys);
Keys1.Sort();
this.listbox1.DataSource = Keys1;
 
pinkfloydfan said:
Hi there

In a Form I have created I am trying to Sort a List<string> extracted
from the Keys of a Dictionary. However, when I attempt to build the
project I get the following error:

Cannot implicitly convert type 'void' to 'object'

The relevant code is as follows:

private void Form1_Load(object sender, EventArgs e)
{
List<string> Keys1 = new
List<string>(Class1.Dictionary1.Keys);
this.listbox1.DataSource = Keys1.Sort();

replace the line above by:
Keys.Sort();
this.listbox1.DataSource = Keys;
}

Without the Sort it works fine but the Keys are obviously not sorted.

Sort doesn't return a sorted list, but sorts the list in place.

Christof
 
pinkfloydfan said:
Hi there

In a Form I have created I am trying to Sort a List<string> extracted
from the Keys of a Dictionary. However, when I attempt to build the
project I get the following error:

Cannot implicitly convert type 'void' to 'object'

The relevant code is as follows:

private void Form1_Load(object sender, EventArgs e)
{
List<string> Keys1 = new
List<string>(Class1.Dictionary1.Keys);
this.listbox1.DataSource = Keys1.Sort();
}


The problem is the assignment. Sort() returns void.

List<string> Keys1 =
new List<string>(Class1.Dictionary1.Keys);
Keys1.Sort();
this.listbox1.DataSource = Keys1;
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top