【发布时间】:2019-06-29 08:36:25
【问题描述】:
我正在尝试使用 LINQ 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 过滤, 请帮助,非常感谢
【问题讨论】:
-
我不确定我是否理解问题所在。能否提供示例数据和预期输出?
-
假设你走到每个人面前问他们是否 (
Where) 有一个孩子,其中一部分名字是Matt(Any和Contains)。莎莉有两个孩子——马修和凯茜。她符合标准。如果你问她她的孩子叫什么名字,她会怎么回答?你会如何解决你的问题?
标签: c# linq collections