繁体   English   中英

如何使嵌套的foreach循环方法通用

[英]How to make nested foreach loop method generic

我想获取所有(唯一)Apple(或Oranges)对象的列表:

var theBigFruitsList = new List<Fruits>{
    new Fruits(){
        Apples = new List<Apple>{
                new Apple { Id = 1 },
                new Apple { Id = 2 }
            }
        },
        Oranges = new List<Orange>{
                new Orange { Id = 4 },
                new Orange { Id = 5 }
            }
        },
        FruitBoolean = False,
        FruitCount = 4,
    },
    new Fruits(){
        Apples = new List<Apple>{
                new Apple { Id = 3 },
                new Apple { Id = 1 },
            }
        },
        Oranges = new List<Orange>{
                new Orange { Id = 6 },
            }
        }
        FruitBoolean = False,
        FruitCount = 3,
    }
}

我为它写了这个方法:

public static List<Apple> GetApplesFromBigFruitsList(List<Fruits> theBigFruitsList )
{
    var dc = new Dictionary<long, Apple>();
    foreach (var fruits in theBigFruitsList)
    {
        foreach (var apple in fruits.Apples)
        {
            if (!dc.ContainsKey(apple.Id))
                dc.Add(apple.Id, apple);
        }
    }
    return dc.Values.ToList();
}

但是,除了苹果和橙子之外,object 中还有许多其他类型的“水果”,我有超过 10 次这种方法,其中苹果这个词只是被橙子取代了。让它通用是有意义的。

我写了这个 function 但它给出了一个错误,因为 Fruits class 没有实现枚举器。 请帮忙!

    public static List<T> FilterFruits<T>(T typeToGet, List<Fruits> theBigFruitsList)
    {
        List<T> fruitResult = new List<T>();

        var fruitType = typeToGet.GetType();

        foreach (var fruits in theBigFruitsList)
        {
            foreach (var fruit in fruits) //errors, intention is to loop over all properties in the Fruits entity to find one specific type
                if (fruit.GetType() == fruitType) //check if type is Apple
                {
                    fruitResult.AddRange(fruits); //add the Apples to a list
                }
        }
        return fruitResult;
    }

课程:

public class Fruits{
    public List<Apple> Apples { get; set; }
    public List<Orange> Oranges { get; set; }
    public List<Pineapple> Pineapples { get; set; }
    public List<Mango> Mangos { get; set; }
    public bool FruitBoolean { get; set; }
    public long FruitCount { get; set; }
    }
public class Apple{
    public long Id { get; set; }
}
public class Orange{
    public long Id { get; set; }
}   
public class Pineapple{
    public long Id { get; set; }
}   
public class Mango{
    public long Id { get; set; }
}   

所需的方法结果:

var Apples = List<Apple>{
    new Apple { Id = 1 },
    new Apple { Id = 2 },
    new Apple { Id = 3 }
}

有一个大清单

将每种水果存储在自己的单独列表中是……很奇怪。 我建议您将它们组合在一个列表中。 如果您无法更改设计,则可以在运行时将它们组合起来,如下所示:

IEnumerable<object> GetAllFruits(Fruits bigFruitlist)
{
    return ((IEnumerable<object>)bigFruitlist.Apples) 
    .Concat((IEnumerable<object>)bigFruitlist.Oranges) 
    .Concat((IEnumerable<object>)bigFruitlist.Mangoes) 
    .Concat((IEnumerable<object>)bigFruitlist.Pineapples); 
}

当然,如果你所有的水果都有一个共同的接口会更好——那么你就不需要IEnumerable<object> ——但如果你也不能做出改变,这仍然可以工作。

获得组合列表后,rest 很容易:

List<T> FilterFruits<T>(Fruits bigFruitlist)
{
    return GetAllFruits(bigFruitList).OfType<T>().ToList();
}

使用列表数组

如果出于某种原因您想避免枚举所有列表(即列表很大并且性能是一个问题),您也可以使用列表数组来做到这一点。

object[] GetAllFruitLists(Fruits bigFruitlist)
{
    return new object[]
    {
        bigFruitlist.Apples,
        bigFruitlist.Oranges,
        bigFruitlist.Mangoes, 
        bigFruitlist.Pineapples
    }; 
}

List<T> FilterFruits<T>(Fruits bigFruitlist)
{
    return GetAllFruitLists(bigFruitList).OfType<List<T>>();
}

要在运行时询问对象的类型,请使用反射。 像这样:

public static List<T> FilterFruits<T>(List<Fruits> fruitsList) where T : IFruit
{
    List<T> fruitResult = new List<T>();

    var fruitType = typeof(T);

    foreach (var fruits in fruitsList)
    {
        foreach (var fp in typeof(Fruits).GetProperties())
        {
            if (fp.PropertyType == typeof(List<T>)) //check if type is Apple
            {
                fruitResult.AddRange((List<T>)(object)fp.GetValue(fruits)); //add the Apples to a list
            }
        }
    }
    return fruitResult;
} 

要在没有反射的情况下执行此操作(在某些情况下可能太慢),您可以执行以下操作:

public static List<T> GetDistinct<T>( IEnumerable<Fruits> fruitsList) where T : IFruit
{
    var ft = typeof(T);
    Func<Fruits, List<T>> picker;

    if (ft == typeof(Apple))
    {
        picker = (fruits) => (List<T>)(object)fruits.Apples;
    }
    else if (ft == typeof(Mango))
    {
        picker = (fruits) => (List<T>)(object)fruits.Mangos;
    }
    else
    {
        throw new NotImplementedException($"Fruit Type {ft.Name} not supported");
    }

    var rv = new Dictionary<long, T>();
    foreach (var t in fruitsList.SelectMany(picker))
    {
        if (!rv.ContainsKey(t.Id))
        {
            rv.Add(t.Id, t);
        }
    }

    return rv.Values.ToList();


}

暂无
暂无

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

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