views:

10487

answers:

5

What is the correct syntax for this:

IList<string> names = "Tom,Scott,Bob".Split(',').ToList<string>().Reverse();

What am I messing up? What does TSource mean?

A: 

Try this:

List<string> names = new List<string>("Tom,Scott,Bob".Split(','));
names.Reverse();
Y Low
I get the error - Cannot implicitly convert type 'void' to 'System.Collections.Generic.List<string>
tyndall
I just tried it and it worked perfectly
Y Low
+19  A: 

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

Jon Skeet
skeet's a beast!
flesh
+1  A: 
List<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList();

This one works.

Rune Grimstad
+1  A: 

What your missing here is that .Reverse() is a void method. It's not possible to assign the result of .Reverse() to a variable. You can however alter the order to use Enumerable.Reverse() and get your result

var x = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>()

The difference is that Enumerable.Reverse() returns an IEnumerable<T> instead of being void return

JaredPar
+1  A: 

Or we can use LINQ to get the same result

var result = from s in "Tom,Scott,Bob".Split(',') orderby s descending select s;
Rohan West