![](/img/trans.png)
[英]How can I add an element to a list that is sorted so that it keeps sorted?
[英]How can I store an object by key in a sorted list?
我有兩節課。 一個 class 是一個 object 類型
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;
}
}
而第二個 class 存儲一個 sortedList 像 SortedList <int, object> Park {get; }
public class sortedList : FileEvent, Gride
{
SortedList<int, object> Park { get; }
public sortedList()
{
Park = new SortedList<int, object>();
}
}
在 function 中 class sortedList FileEvent.scanFile (string pathFile) 我用鍵和出租車 object 填寫排序列表。 在這一行 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);
}
}
}
** 如何從排序列表中取回出租車 object 和 object 中的數據?**
使用SortedList<int, Taksi>
代替SortedList<int, object>
。 如果您在此處指定正確的類型,則該列表知道它包含什么類型的對象,您可以將它們作為正確的類型訪問。
為了從列表中按數字獲取 taksi,您可以使用TryGetValue
方法:
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
}
如果您確定某個數字在列表中,您可以使用方括號訪問它:
Taksi no42 = Park[42];
為了遍歷列表中的所有對象:
foreach(Taksi taksi in Park.Values)
{
// Do something with taksi
}
或者,如果您想訪問 object 及其在列表中添加的編號:
foreach(var pair in Park)
{
// pair.Key is the number
// pair.Value is the Taksi object
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.