Linq查询在嵌套对象中查找对象

时间:2015-11-12 00:42:57

标签: c# linq nested-loops

下面附有完整的代码。我想找到所有具有特定颜色的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; }
    }

}

1 个答案:

答案 0 :(得分:2)

你可以使用类似的东西:

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样式。