Mike
Mike

Reputation: 3284

How do I cast this using LINQ?

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

Upvotes: 2

Views: 170

Answers (2)

Ani
Ani

Reputation: 113412

I suggest using this constructor of ObservableCollection<T>, which lets you construct the collection from an existing IEnumerable<T>.

In C# 4, you can do:

return new ObservableCollection<ISelectableItem>
           (units.Select(item => new SelectableUnit(item)));

Because of the covariance of the IEnumerable<T> interface, an IEnumerable<SelectableUnit> can be seen as an IEnumerable<ISelectableItem>.

In C# 3, which does not support variance in generic interfaces, you can do:

return new ObservableCollection<ISelectableItem>
           (units.Select(item => new SelectableUnit(item)).Cast<ISelectableItem>());

(or)

 return new ObservableCollection<ISelectableItem>
               (units.Select(item => (ISelectableItem)new SelectableUnit(item)));

If you are doing this sort of thing often, consider writing a ToObservableCollection() extension- method on IEnumerable<T> to let type-inference and/or method-chaining work in your favour.

Upvotes: 6

sehe
sehe

Reputation: 393064

In C# 3/ .Net 3.5

return new ObservableCollection<ISelectableItem>
           (units.Select(item => new SelectableUnit(item)).Cast<ISelectableItem>());

Upvotes: 0

Related Questions