首页 > 解决方案 > 过滤对象集合内的集合不起作用

问题描述

我正在尝试使用 LINQ Any 运算符过滤列表中的子列表,尽管 Any 运算符在许多站点中是此类问题的批准答案,但该问题仍无法正常工作,我有每个 Group Object 都有一个列表 Vehicles 的 Group 对象列表,我正在尝试使用车牌号过滤每个组内的车辆的问题

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

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 过滤,请帮助,非常感谢

标签: c#linqcollections

解决方案


您正在做的是lstGrps在您想要过滤每个组Vehicles列表时进行过滤。

在您的代码filteredIEnumerable<Group>,每个Group都至少有一个Vehiclecontains VehiclesPlatNo并且"A0-"因为此条件对所有Groups 都为真,所以不会过滤任何内容。

试试这个代码:

Seed seed = new Seed();
var groups = seed.SeedGroupsVehicles();
var filteredGroups = groups
    .Select(g => new Group {
        Id = g.Id,
        Name = g.Name,
        // Here is where you filter Vehicles
        Vehicles = g.Vehicles.Where(v => v.PlateNo.Contains("A0-")),
    });

推荐阅读