tags:

views:

186

answers:

2

Check the code.

class DynamicObj : BaseObj {}
class BaseObj {}

class clientCode 
{
   List<DynamicObj> GetFilteredObjs(List<BaseObj> baseList) 
   {
        // I want to return the sublist of baseList which only have DynamicObj.
        List<DynamicObj> dList = baseList.FindAll(
                                          delegate(BaseObj bo){        // Del1
                                          return bo is DynamicObj;
                                          }).ConvertAll<DynamicObj>(
                                             delegate(BaseObj bo){     // Del2 
                                             return bo as DynamicObj;
                                             });   

   }
}

Now it might be a silly question, But my code will have to loop objects 2 times,once for Del1 loop and once for Del2 loop.

Is there any straight way? C# 2.0 only.

+1  A: 

The easiest way is probably to use an iterator block:

public IEnumerable<TTarget> FilteredCast<TSource,TTarget>
    (IEnumerable<TSource> source)
    where TSource : class
    where TTarget : class, TSource
{
    foreach (TSource element in source)
    {
        TTarget converted = element as TTarget;
        if (converted != null)
        {
            yield return converted;
        }
    }
}

(This is basically the Enumerable.OfType method in LINQ to Objects, btw. I've restricted it to reference types for convenience, but it's still generic so you can reuse it more easily.)

Then just write:

List<DynamicObj> GetFilteredObjs(List<BaseObj> baseList) 
{
    return new List<DynamicObj>(FilteredCast<BaseObj,DynamicObj>(baseList);
}

Note that this won't return nulls. If you want nulls to be included, you'd need to cater for that explicitly.

Jon Skeet
+2  A: 

Sure:

IEnumerable<DynamicObj> GetDynamicObjects(IEnumerable<BaseObj> baseList)
{
    foreach(BaseObj baseObj in baseList)
        if(baseObj is DynamicObj)
            yield return (DynamicObj)baseObj;
}

List<DynamicObj> dynamicList = new List<DynamicObj>(GetDynamicObjects(...));
Anton Gogolev