I have a helper class that I am using to return the selected items in a number of IEnumerable POCO collection but I'm not happy with the implementation. One of the reasons for using this method is that the collections area returned by RIA services as ReadOnlyObservableCollections and I don't believe they support LINQ but may be wrong.
Is there a way to refactor these three methods using generics? Are there any other improvements that I can make?
public class ModelHelper : IModelHelper
{
public IList<Int32> GetSelectedResults(IEnumerable<FaultAuditScoresDto> scores)
{
IList<Int32> selected = new List<Int32>();
foreach (FaultAuditScoresDto s in scores)
{
if (s.IsSelected)
{
selected.Add(s.ID);
}
}
return selected;
}
public IList<Int32> GetSelectedResults(IEnumerable<ZonesDto> zones)
{
IList<Int32> selected = new List<Int32>();
foreach (ZonesDto s in zones)
{
if (s.IsSelected)
{
selected.Add(s.ID);
}
}
return selected;
}
public IList<Int32> GetSelectedResults(IEnumerable<FaultAreasDto> faultAreas)
{
IList<Int32> selected = new List<Int32>();
foreach (FaultAreasDto s in faultAreas)
{
if (s.IsSelected)
{
selected.Add(s.ID);
}
}
return selected;
}
}
I have refactored it to use generics and a dynamic type for the loop but I'm still not happy with it
public IList<T> GetSelectedResults<T,U>(IEnumerable<U> scores)
{
List<T> selected = new List<T>();
foreach (dynamic s in scores)
{
if (s.IsSelected)
{
//Need to cast the ID as <T> due to the IList limitation below
//http://connect.microsoft.com/VisualStudio/feedback/details/534288/ilist-dynamic-cannot-call-a-method-add-without-casting
selected.Add((T)s.ID);
}
}
return selected;
}
Any other idea?