Simon Gamlieli
Simon Gamlieli

Reputation: 129

How can i sort a List<string> by name?

In form1 top i have:

public List<string> imageList = new List<string>();

Then in the constructor first i tried to use only this:

this.imageList = Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp").ToList();

But it didn't list the files in order as they are on the hard disk.

Now i tried this:

this.imageList = from file in Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp")
                        orderby file descending
                        select file.ToList();

But I'm getting error on the select:

Error 2 Cannot implicitly convert type System.Collections.Generic.IEnumerable> to System.Collections.Generic.List`. An explicit conversion exists (are you missing a cast?)

Upvotes: 0

Views: 93

Answers (5)

David L
David L

Reputation: 33833

Wrap your query appropriately. As it currently is written, you're trying to convert a list of chars (the result of calling ToList() on a string) to a list of strings since you're actually calling ToList() on the file itself instead of on the collection of files.

this.imageList = 
    (from file in Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp")
        orderby file descending
        select file).ToList();

Upvotes: 4

gilly3
gilly3

Reputation: 91497

I prefer the method syntax over the sql syntax. Call .OrderBy(f => f) before you call .ToList().

Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp").OrderBy(f => f).ToList();

Or, use .OrderByDescending():

Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp").OrderByDescending(f => f).ToList();

Upvotes: 0

Bas
Bas

Reputation: 27105

You are (almost) there. The problem you have is in the ToList call, which curiously works for strings as well, since it's an IEnumerable<char>. Instead make sure you write parentheses around your Linq query before doing any operation on its result, such as ToList.

this.imageList = 
    (from file in Directory.GetFiles(@"e:\webbrowserimages\", "*.bmp")
                    orderby file descending
                    select file).ToList();

Upvotes: 1

SLaks
SLaks

Reputation: 887547

file.ToList()

file is a string, which implements IEnumerable<char>.

Therefore, file.ToList() is a List<char>, which you're selecting as the results of your query. This produces a collection of List<char>s, which is not what you want.

You need to wrap the query in parentheses to call .ToList() on the query itself.

Upvotes: 3

Related Questions