[英]Simple lookup function
我有一個簡單的結構,我想用作查找表:
public struct TileTypeSize
{
public string type;
public Size size;
public TileTypeSize(string typeIn, Size sizeIn)
{
type = typeIn;
size = sizeIn;
}
}
我這樣填充這個:
tileTypeSizeList.Add(new TileTypeSize("W",rectangleSizeWall));
tileTypeSizeList.Add(new TileTypeSize("p",rectangleSizePill));
tileTypeSizeList.Add(new TileTypeSize("P",rectangleSizePowerPill));
tileTypeSizeList.Add(new TileTypeSize("_",rectangleSizeWall));
tileTypeSizeList.Add(new TileTypeSize("=",rectangleSizeWall));
查找給定類型的大小的最有效方法是什么?
提前致謝!
如果您知道集合中只有一個匹配項,那么您可以使用:
var size = tileTypeSizeList.Single(t => t.type == someType).size;
如果沒有,你必須更加聰明才能正確處理找不到匹配項的情況:
Size size;
var match =
tileTypeSizeList
.Cast<TileTypeSize?>().FirstOrDefault(t => t.type == someType);
if(match != null) size = match.size;
但請記住,如果這是結構中唯一的數據,則有更好的方法來存儲此信息。 我建議使用Dictionary<string, Size>
。
通常 ,最有效的方法是將數據放入Dictionary
或類似的容器中( SortedDictionary
和SortedList
與Dictionary
有很小的差異,在某些情況下更適合):
var dict = new Dictionary<string, Size>
{
{ "W", rectangleSizeWall },
// etc
}
接着:
var size = dict["W"];
如果有理由,您當然可以按字典順序迭代字典中的值。
如果您將要查找5種類型 (即問題的大小非常小),那么像您這樣的直接列表可能比關聯容器更快。 所以:
var tileStruct = tileTypeSizeList.FirstOrDefault(s => s.type == "W");
if (tileStruct.type == "") {
// not found
}
else {
var size = tileStruct.size;
}
如果您確定永遠不會有搜索錯過,您可以刪除“如果找到”檢查。
var type = tileTypeSizeList.FirstOrDefault(t => t.type == someType);
if(type==null) throw new NotFoundException();
return type.size;
但是如果列表很大並且您需要經常查找數據,那么最好在其他答案中注意使用Dictionary
。
使用Dictionary而不是List:
Dictionary<string, TileTypeSize> tileTypeSizeDictionary = Dictionary<string, TileTypeSize>();
tileTypeSizeDictionary.Add("W", new TileTypeSize("W",rectangleSizeWall));
...
您使用以下內容查找元素:
TileTypeSize rectangleSizeWall = tileTypeSizeDictionary["W"];
當您需要按鍵查找時,字典比列表更快。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.