擴充方法無法定義索引器(this[]),C# 語法限制。若需 list["key"] 語法,必須自訂類別繼承 List<T> 並定義索引器。
public class KeyedList : List where T : IKeyed {
public T this[string key] {
get => this.FirstOrDefault(x => x.Key == key);
set {
var idx = this.FindIndex(x => x.Key == key);
if (idx >= 0) this[idx] = value;
else this.Add(value);
}
}
}
public interface IKeyed {
string Key { get; }
}
public class Room : IKeyed {
public string RoomNo { get; set; }
public string Key => RoomNo; // 以 RoomNo 為鍵
}
var rooms = new KeyedList();
rooms.Add(new Room { RoomNo = "101" });
Room r = rooms["101"]; // 直接用字串索引
list.FirstOrDefault(x => x.RoomNo == "101"),語意清晰無需新類別。