我有一个 List<KeyValuePair<string, othertype>>
.我需要按照以下方式做一些事情
list.Find(x=>x.Key=="foobar")
但是,如果列表中不存在,行为会是什么?通常它会返回 null,但结构不能为 null。
最佳答案
我的建议是对不可为 null 的类型使用 FindIndex
int index = list.FindIndex(x => x.Key == "foobar");
if (index >= 0) {
// found!
UseResult(list[index]);
}
如果Find()
不成功,返回默认值default(T)
。对于不可空类型,此结果无法与具有默认值的常规条目区分开来。当列表可能包含常规的 null
条目时,对于可为 null 的类型也是如此。
关于c# - 当 T 是结构时,List<T>.Find 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12676209/