使用IEnumerable对列表进行排序 - XAML

时间:2017-02-25 22:25:59

标签: c# xaml

我有一个车辆列表和一个空的IEnumerable。当用户更改XAML顶部的单选按钮时,我想从列表中删除与VehicleType不匹配的某些车辆

我的问题:如何删除并显示用户指示的不具有相同字符串类型(属性中的VehicleType)的车辆列表

代码:

 public List<Vehicle> VehicleList = new List<Vehicle>();
    public IEnumerable<Vehicle> FilteredVehicleList = new List<Vehicle>();

        private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        Vehicle v1 = new Car() { Make = "Ford", Model = "Fiesta", Price = 10000, Year = "1999", Colour = "Red", Mileage = 40000, Description = "Lovely red car, 4 wheel, optional steering wheel.", VehicleType = "Car"};
        VehicleList.Add(v1);
        Vehicle v2 = new Car() { Make = "Ford", Model = "Mondeo", Price = 20000, Year = "2001", Colour = "Green", Mileage = 36000, Description = "Lovely green car, 4 wheel, optional steering wheel.", VehicleType = "Car" };
        VehicleList.Add(v2);
        Vehicle v3 = new Car() { Make = "Ford", Model = "Fiesta", Price = 15000, Year = "2003", Colour = "Silver", Mileage = 14000, Description = "Lovely silver car, 4 wheel, optional steering wheel.", VehicleType = "Car" };
        VehicleList.Add(v3);
        Vehicle v4 = new Car() { Make = "Opel", Model = "Astra", Price = 25000, Year = "2002", Colour = "Silver", Mileage = 27000, Description = "Lovely silver car, 4 wheel, optional steering wheel.", VehicleType = "Car" };
        VehicleList.Add(v4);
        Vehicle v5 = new Bike() { Make = "Kawasaki", Model = "ZX", Price = 30000, Year = "2008", Colour = "Black", Mileage = 25000, Description = "Lovely black bike, 2 wheel, no optional steering wheel.", VehicleType = "Bike" };
        VehicleList.Add(v5);

        listbox_cars.ItemsSource = VehicleList;

        string[] filterBox = { "All", "Price", "Mileage", "Make" };
        comboBox_sortCars.ItemsSource = filterBox;
        comboBox_sortCars.SelectedIndex = 0;
    }

        private void comboBox_sortCars_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var output = listbox_cars.ItemsSource;
        string sortBy = comboBox_sortCars.SelectedValue.ToString();

        switch (sortBy)
        {
            case "All":
                output = VehicleList;
                break;

            case "Make":
                FilteredVehicleList = VehicleList.OrderBy(i => i.Make);
                output = FilteredVehicleList;
                break;

            case "Price":
                FilteredVehicleList = VehicleList.OrderBy(i => i.Price);
                output = FilteredVehicleList;
                break;

            case "Mileage":
                FilteredVehicleList = VehicleList.OrderBy(i => i.Mileage);
                output = FilteredVehicleList;
                break;
        } 

1 个答案:

答案 0 :(得分:0)

切换后必须设置ItemsSource

listbox_cars.ItemsSource = output;