过滤对象集合内部的集合不起作用

时间:2019-06-29 08:36:25

标签: c# linq collections

我正在尝试使用LINQ Any运算符过滤列表中的子列表,尽管在许多站点中Any运算符都可以解决该问题,但Any运算符仍无法正常工作的问题, 我有一个“组对象”列表,每个“组对象”都有一个“车辆”列表,我正在尝试使用板号

过滤每个组内的车辆的问题

请检查下面为检查此问题而创建的代码

using System;
using System.Linq;
using System.Collections.Generic;
namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            Seed seed = new Seed();
            seed.SeedGroupsVehicles();
            List<Group> lstGrps =seed.SeedGroupsVehicles();
            // Linq Query to filter Vehicles inside each group 
            var filtered = lstGrps
                .Where(s => s.Vehicles.Any(vehicle => vehicle.PlateNo.Contains("A0-")))
                .GroupBy(p=>p.Name);
            List<Group> lstfilteredGroup = filtered.SelectMany(f => f).ToList();
            // Print Filtered Groups 
            foreach(var grp in lstfilteredGroup)
            {
                Console.WriteLine(" Group {0} {1}" , grp.Id,grp.Name);
                foreach (var vehicle in grp.Vehicles)
                {
                    Console.WriteLine("\tVehicle {0} {1} {2}",vehicle.Id,vehicle.Name,vehicle.PlateNo);
                }
            }

        }
    }

    public class Seed
    {
        public List<Group> SeedGroupsVehicles()
        {
            // Create two groups each group has ten vehicles 
            Group[] arrGroups = new Group[2];
            string[] vehiclesPLateNums = new string[] { "A0-3456790", "A0-3440999", "A0-2354543", "A0-5345346", "LP-ZA32554", "LP-3445464", "LP-3590324", "LP-3423535", "LP-2352569", "LP-5435XCF" };
            string[] vehiclesNames = new string[] { "V1", "V2", "V3", "V14", "V5", "V6", "V7", "V8", "V9", "V10" };
            List<Vehicle> lstvehicles;
            for (int index = 0; index < arrGroups.Length; index++)
            {
                lstvehicles = new List<Vehicle>();
                Vehicle vehicle = new Vehicle();
                for (int vehicleIndex = 0; vehicleIndex < vehiclesNames.Length; vehicleIndex++)
                {
                    lstvehicles.Add(new Vehicle() { Id= vehicleIndex + 1 , Name=vehiclesNames[vehicleIndex],PlateNo=vehiclesPLateNums[vehicleIndex] });
                }
                arrGroups[index] =  new Group() { Id = index+1, Name = "group " + index+1, Vehicles = lstvehicles } ; 
            }
            return arrGroups.ToList();
        }
    }
}

打印每组的车辆后,我注意到每组的车辆都没有基于具有字符串“ A0”的PlateNo进行过滤, 请帮助,非常感谢

1 个答案:

答案 0 :(得分:1)

您要过滤lstGrps的同时要过滤每个Vehicles组列表。

在您的代码中filtered将是一个IEnumerable<Group>,其中每个GroupVehicle中至少有一个Vehicles,其PlatNo包含{ {1}},并且由于所有"A0-"都适用此条件,因此不会过滤任何内容。

尝试以下代码:

Group