c# - 当 T 是结构时,List<T>.Find 如何工作?

标签 c# .net list generics struct

我有一个 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/

相关文章:

c# - 如何以 “12”的格式显示数字 “0000012”

c# - 如何为 Odata 创建按 Id 获取的查询表达式

c# - 什么是最快的 WinForms 控件套件(商业)

python - 将列表附加到字典

jquery - 使用 jquery 根据 li 元素对 ul 列表进行排序?

c# - 保存域实体更改

c# - 提取数据库特定 id :s with the repository pattern?

c# - 为什么 C# 不推断我的泛型类型?

c# - 在 LINQ 中,如何修改现有的 LINQ 扩展方法以添加 "By"选择器,即将 Func<T> TResult 添加到函数签名?

list - 将列表与 AutoBean 一起使用