Linq查询可在嵌套对象中查找对象
本文关键字:对象 查找 嵌套 查询 Linq | 更新日期: 2023-09-27 18:21:31
下面附有完整的代码。我想找到所有具有特定颜色的Cars对象。
车辆列表由两个类型为Cars的列表组成。"汽车"列表由"颜色"类型的对象组成。
不使用foreach迭代,Linq查询会是什么样子?
using System.Collections.Generic;
public class Test
{
public void testitall()
{
List<Cars> test = FindCarByColour("Red");
}
/// <summary>
/// Find all cars with property ColourName like colourcriteria
/// </summary>
/// <param name="colourcriteria"></param>
/// <returns></returns>
private List<Cars> FindCarByColour(string colourcriteria)
{
// Populate data classes
Colours Col1 = new Colours();
Col1.ColourName ="Red";
Colours Col2 = new Colours();
Col2.ColourName ="Blue";
List<Cars> CarList1 = new List<Cars>();
CarList1.Add(new Cars { Name = "Saab", ColourProperties = Col1 });
CarList1.Add(new Cars { Name = "Citroen", ColourProperties = Col2});
List<Cars> CarList2 = new List<Cars>();
CarList2.Add(new Cars { Name = "Daf", ColourProperties = Col1 });
CarList2.Add(new Cars { Name = "Vauxhall", ColourProperties = Col2 });
List<Vehicles> vehicleList = new List<Vehicles>();
vehicleList.Add(new Vehicles { Vechicle = "SmallCar", Cars = CarList1 });
vehicleList.Add(new Vehicles { Vechicle = "MediumCar", Cars = CarList2 });
// Search
List<Cars> ListOfFindings = new List<Cars>();
foreach (Vehicles vehicleItem in vehicleList)
{
foreach (Cars caritem in vehicleItem.Cars)
{
if (caritem.Name != null && caritem.ColourProperties.ColourName == colourcriteria)
{
ListOfFindings.Add(caritem);
}
}
}
return ListOfFindings;
}
// Data classes
public class Vehicles
{
public string Vechicle { get; set; }
public List<Cars> Cars { get; set; }
}
public class Cars
{
public string Name { get; set; }
public Colours ColourProperties { get; set; }
}
public class Colours
{
public string ColourName { get; set; }
}
}
您可能会使用以下内容
var listOfFindings = (from vehicleItem in vehicleList
from carItem in vehicleItem.Cars
where carItem.Name != null
&& carItem.ColourProperties.ColourName == colourcriteria
select carItem).ToList();
或
var listOfFindings = vehicleList.SelectMany(vehicleItem => vehicleItem.Cars).Where(carItem => carItem.Name != null && carItem.ColourProperties.ColourName == colourcriteria).ToList();
取决于您想要使用的Linq风格。