I have the following snippet, my question is, how do I cast this using a simplified syntax, maybe using LINQ syntax?
private ObservableCollection<ISelectableItem> GetSelectableUnits(ObservableCollection<Unit> units)
{
var selectableUnits = new ObservableCollection<ISelectableItem>();
units.ToList().ForEach(item=>selectableUnits.Add(new SelectableUnit(item)));
return selectableUnits;
}
Note:SelectableUnit implements ISelectableItem.
Thanks,
-Mike
I suggest using this constructor of
ObservableCollection<T>, which lets you construct the collection from an existingIEnumerable<T>.In C# 4, you can do:
Because of the covariance of the
IEnumerable<T>interface, anIEnumerable<SelectableUnit>can be seen as anIEnumerable<ISelectableItem>.In C# 3, which does not support variance in generic interfaces, you can do:
(or)
If you are doing this sort of thing often, consider writing a
ToObservableCollection()extension- method onIEnumerable<T>to let type-inference and/or method-chaining work in your favour.