Compare car costs including long term mileage in C#

Datetime:2016-08-22 22:12:20         Topic: C#          Share        Original >>
Here to See The Original Article!!!

This example calculates the total car costs including gas use. Some cars that seem less expensive than others actually cost more in the long run because they get worse gas mileage.

Enter the total number of city and highway miles of driving you expect over the life of the car and the gas price per gallon. Then click the Calculate button to see the results. Click on the ListView’s columns to sort by that column.

This example uses the following CarData class to hold information about a type of car.

private class CarData
    public string Name;
    public float CityMileage, HwyMileage, BaseCost;
    public CarData(string name, float city_mileage,
        float hwy_mileage, float base_cost)
        Name = name;
        CityMileage = city_mileage;
        HwyMileage = hwy_mileage;
        BaseCost = base_cost;
private List<CarData> Cars = new List<CarData>();

The following code shows how the program calculates and displays total car costs.

// Calculate total cost including fuel.
private void CalculateTotalCosts()
        // Calculate the costs.
        float city_miles = float.Parse(txtCityMiles.Text);
        float hwy_miles = float.Parse(txtHwyMiles.Text);
        float cost_per_gallon = float.Parse(txtCostPerGallon.Text,
        foreach (CarData car_data in Cars)
            ListViewItem car_item =
            float total_cost =
                car_data.BaseCost +
                cost_per_gallon * city_miles / car_data.CityMileage +
                cost_per_gallon * hwy_miles / car_data.HwyMileage;

This code loops through the CarData objects adding their data to the ListView . It displays the car’s name, base cost, city mileage, and highway mileage. It then calculates the total car costs including fuel and displays that.

This program uses the techniques described in the post Sort a ListView using the column you click in C# to let you sort the columns.

Note that there are many other factors to consider when choosing a car. Some cars have higher repair costs or are more likely to need repairs. And no one drives a Mercedes-Benz E350 because it saves at the pump.

Also I suspect some of these cars are more likely to last much longer than others. A less expensive car might last around 100,000 or 120,000 miles while a more expensive model might last 200,000 miles. If you factor in the cost of buying a second cheap car, buying the more expensive model may be much cheaper in the long run.

About List