【发布时间】:2015-11-12 00:42:56
【问题描述】:
完整的代码附在下面。我想找到所有具有某种颜色的 Cars 对象。
Vehicles 列表由两个 Cars 类型的列表组成。 Cars 列表由 Colours 类型的对象组成。
不使用 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; }
}
}
【问题讨论】:
-
试试这个:List
ListOfFindings = vehicleList.SelectMany(x => (List )x.Cars).Where(y => y.ColourProperties.ColourName == colourcriteria)。 ToList();
标签: c# linq nested-loops