简体   繁体   English

泛型子列表

[英]Generics Sub List

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. 现在这可能是一个愚蠢的问题,但是我的代码将必须循环对象两次,一次是Del1循环,一次是Del2循环。

Is there any straight way? 有没有直接的方法? C# 2.0 only. 仅C#2.0。

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.) (顺便说一下,这基本上是LINQ to Objects中的Enumerable.OfType方法。为方便起见,我将其限制为引用类型,但是它仍然是通用的,因此您可以更轻松地重用它。)

Then just write: 然后写:

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

Note that this won't return nulls. 请注意,这不会返回null。 If you want nulls to be included, you'd need to cater for that explicitly. 如果要包含空值,则需要明确地满足此要求。

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(...));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM