Search code examples
c#objectsortedlist

How can I store an object by key in a sorted list?


I have two classes. One class is an object of the type

public class Taksi
{
    public int num;
    public string brand;
    public string FIO;
    public double mileage;
    // Here i missed get and setters

    public Taksi(int newNum, string newBrand, string newFio, double Mileage)
    {
        this.brand = newBrand;
        this.FIO = newFio;
        this.mileage = Mileage;
        this.num = newNum;
    }
}

And the second class stores a sortedList like SortedList <int, object> Park {get; }

public class sortedList : FileEvent, Gride
{
    SortedList<int, object> Park { get; }

    public sortedList()
    {
        Park = new SortedList<int, object>();
    }
 }

in function in class sortedList FileEvent.scanFile (string pathFile) I fill in the sorted list with the keys and the Taxi object. in this line Park.Add(Int32.Parse(dataArray[0]), newTaksi);

void FileEvent.scanFile(string pathFile)
{
    Taksi newTaksi;
    IEnumerable<string> lines = Enumerable.Empty<string>();

    try
    {
        lines = File.ReadLines(pathFile);
    }
    catch (Exception e)
    {
        MessageBox.Show("Exception when opening file: " + e);
    }

    foreach (var line in lines)
    {
        try
        {
            string[] dataArray = line.Split('|');
            newTaksi = new Taksi(Int32.Parse(dataArray[0]),
                dataArray[1],
                dataArray[2],
                double.Parse(dataArray[3]));

            Park.Add(Int32.Parse(dataArray[0]), newTaksi);
        }
        catch (Exception e)
        {
            MessageBox.Show("Exception when parsing file: " + e);
        }
    }
}

** How can I get back the taxi object from the sorted list and the data from the object?**


Solution

  • Use SortedList<int, Taksi> instead of SortedList<int, object>. If you specify the correct type here, the list knows what type of objects it holds and you can access them as the correct type.

    In order to get a taksi by number from the list, you can use the TryGetValue method:

    if(Park.TryGetValue(42, out Taksi myTaksi))
    {
        // Number 42 was in the list and you can use it here as myTaksi
    }
    else
    {
        // There is no taxi with number 42 in the list
    }
    

    If you are certain that a certain number is in the list, you can access it using square brackets:

    Taksi no42 = Park[42];
    

    In order to loop over all objects in the list:

    foreach(Taksi taksi in Park.Values)
    {
        // Do something with taksi
    }
    

    Or if you want to access the object together with the number it was added under in the list:

    foreach(var pair in Park)
    {
        // pair.Key is the number
        // pair.Value is the Taksi object
    }