views:

228

answers:

3

Does anyone have an extension method to quickly convert the types in a LinkedList<T> using a Converter<TInput, TOutput>?

I'm a bit surprised, where is the ConvertAll<TOutput>(delegate)?

+11  A: 

The ConvertAll equivalent in extension methods for Linq is called Select!

var result = myLinkedList.Select(x => FancyCalculationWith(x))
Konrad Rudolph
+1 Select == "map" (higher order function)
Andrew Hare
Assuming, of course, that LinkedList<T> implements IEnumerable<T>. I am not familiar with LinkedList<T>
Brian Genisio
(The difference being that List.ConvertAll is able to pre-allocate a buffer of the right size of course, as it knows the existing size.)
Jon Skeet
A: 

Depends on what you want to get out of it, but you can use Cast then enumerate through the resulting IEnumerable.

  public class Foo
  {
    ...
  }

  public class Bar : Foo
  {
    ...
  }

  var list = new LinkedList<Bar>();
  .... make list....

  foreach (var foo in list.Cast<Foo>())
  {
      ...
  }
tvanfosson
A: 

As tvanfosson says it is possible to Cast<T> but if you want to avoid an InvalidCastException you can use the OfType<T> extension method which will silently pass over and items in the list that fail the conversion to the type of the generic type parameter you supply.

Andrew Hare