繁体   English   中英

我在一个列表中有多个列表对象,如何获取每个子列表中存在的项目?

[英]I have multiple list objects in one list, how can i get the items that exist in every child list?

从基本的 class 开始:

public class Car
{
  public string Name {get;set;}
}

然后我可以创建这些汽车的列表

List<Car> cars = new List<Car>();

新的步骤是拥有此列表的列表,如下所示:

List<List<Car>> allListsOfCars = new List<List<Car>>();

填充 allListsOfCars 后,我想将它传递给 function,它将返回每个列表列表中存在的汽车。

我知道这听起来很混乱,所以我会尝试多解释一下。

如果我有 ListA、ListB、ListC 所有类型的 List - 现在将它们组合成 1 个保存列表(列表的列表),那么我怎样才能取回每个列表中存在的所有汽车? 例如,如果汽车只存在于 ListA 中,那么我不感兴趣,它需要存在于 ListA AND ListB AND ListC 中,然后我希望将它添加到结果集中并返回。

提前致谢。

您需要找到所有子列表的复合交集。

IEnumerable<Car> result=allListsOfCars.FirstOrDefault();
if(result!=null)
{
    foreach(var sublist in allListsOfCars.Skip(1))
    {
        result=result.Intersect(sublist);
    }
    //enumerate result to run the query
}

可能可以使用Aggregate运算符重写以消除循环,但Aggregate永远不会很好地读取 IMO。

如果列表很长,您可能会使用HashSet获得不错的速度提升

IEnumerable<Car> fst=allListsOfCars.FirstOrDefault();
if(result!=null)
{
    HashSet<Car> hs=new HashSet<Car>(fst);
    foreach(var sublist in allListsOfCars.Skip(1))
    {
        hs.IntersectWith(sublist); //in-place operation
    }
    //enumerate hs
}

确保您的Car class 正确实现了相等成员和GetHashCode ,否则这些方法都不会按预期工作。

如果您有权访问 .NET 3.5 或更高版本,您可以执行以下操作:

IEnumerable<Car> carList = allListsOfCar.SelectMany(cars => cars);

编辑:

要执行列表的交集,您可以执行以下操作:

List<Car> carList = allListsOfCar.Aggregate((left, right) => left.Intersect(right).ToList());

您可以使用 Aggregate,我认为这是一个非常真实的用例:

var allCars = allListOfCars.Aggregate((listAcc,list2)=> listAcc.Concat(list2).ToList());

基本上,对于每个元素(在本例中为 List<> )将其连接到累加器,最后得到一个列表。

我尝试了与亚当相同的方法,但将其扩展了一点。

IEnumerable<Car> carList = listCars.SelectMany(cars => cars);

List<Car> repeatedCars = new List<Car>();

int length = listCars.Count;

foreach (Car c in cars1)
{
    int numberRepeats = carList.Count(car => car.Name == c.Name);
    if (numberRepeats == length)
    {
        repeatedCars.Add(c);
    }
}

基本上,您需要知道您有多少个列表并将它们全部保存在一个列表中。 然后只需遍历第一个汽车列表(或其中任何一个)并计算列表中具有相同名称的汽车的数量以及所有其他列表。 如果长度和重复次数相同,则该车在所有列表中。

暂无
暂无

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

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