c# - 过滤对象集合内的集合不起作用
问题描述
我正在尝试使用 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 过滤,请帮助,非常感谢
解决方案
您正在做的是lstGrps
在您想要过滤每个组Vehicles
列表时进行过滤。
在您的代码filtered
中IEnumerable<Group>
,每个Group
都至少有一个Vehicle
contains Vehicles
,PlatNo
并且"A0-"
因为此条件对所有Group
s 都为真,所以不会过滤任何内容。
试试这个代码:
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-")),
});
推荐阅读
- jenkins - 当用户从 Bitbucket clou 提出拉取请求时,Jenkins 不会得到通知并且不会构建
- php - 如何将不同的html页面值存储到数据库的同一行中?
- python - Running google app sdk dev_appserver.py can't find the local python environment
- kylo - 如何在 Kylo 中添加自定义类别属性?
- iis - Application pool recycling — doesn't recover
- php - For循环在laravel控制器中不起作用
- sage - 欧拉法贤者数学不知从何下手
- java - 文本到语音 (TTS) 延迟 3 秒说出文本
- amazon-web-services - 使用预定事件触发 AWS API Gateway 函数
- php - PHP 错误:在布尔值上调用成员函数 setTimeZone()