tags:

views:

79

answers:

2

Hi, I am trying to fill object[] with List<string> but I cannot figure out how to use ConvertAll. MSDN did not help me. At first I tried to create an instance of Converter but it looks like it expects delegate?

Converter<string, object> conv = new Converter<string, object>(??); //why delegate? 
this.comboBox1.Items.AddRange(Form1.AnimalType.ConvertAll<object>(conv)); 

Thanks :)

A: 

The delegate transforms each member of the collection into the requested type.

If you are trying to convert objects to strings, try something like

conv = o => o.ToString();

If you are trying to convert strings to objects, try something like

conv = ParseStringIntoObject;

object ParseStringIntoObject(string stringRepresentation)
{
  // do whatever you need to do in order to convert your string
}
Hmm then I really miss the point of Converter class. What is the difference between this and writing simple method for conversion?
Petr
Using a Converter will do the "iterate over each item in the list" bit for you - you supply it a delegate, and it applies it to every item in a List (using ConvertAll). This also allows you to separate the conversion logic from the rest of your code - you could use a factory class or something similar to select an appropriate Converter based upon some variable(s).
Graham Clark
A: 

There is no need to convert to object as all types in the .NET runtime inherit from object.

If you want to assign the members of the list Form1.AnimalTypes to a combobox you should can just add them to the Items collection and then you should set DisplayMember to the name of the property you want to display and ValueMember to the name of the property you want to bind.

comboBox.Items.AddRange(Form1.AnimalTypes);
comboBox.DisplayMember = "AnimalTypeName";
comboBox.ValueMember = "AnimalTypeId";

If you want to have just the conversion and the assignment to the combo box does not matter you can do the following:

object[] myArray = Form1.AnimalTypes.ToArray();

The converter class is needed for conversions that are not defined by an object's inheritance, i.e. use converters if you want to convert apples to oranges, but use casts if you want to convert appels or oranges to fruit. In c# 3.0 you can cast a complete collection by using the following snippet:

var newColOfBaseType = myList.Cast<BaseType>();

Using Linq you can also filte the entries of a given type from a collection and then extract a collection of that specific type:

var oranges = fruit.OfType<Orange>().Cast<Orange>();

Using Linq you can also use Select to do a transformation:

var oranges = apples.Select(new Orange() { /* ... and initializers here ...*/});
Obalix