为什么列出. Find()方法将最后一个对象返回为null? [英] Why the List . Find() method return the last object as null ?
本文介绍了为什么列出. Find()方法将最后一个对象返回为null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
代码:
the code:
List<Model.Sys_Permission> sys_permissions = new BLL.Sys_Permission().GetAll();
List<Model.Sys_Permission> sys_permissionsNew = new List<Model.Sys_Permission>();
var tempPermission = new Model.Sys_Permission();
permissionCodes.ForEach(r => {
tempPermission = sys_permissions.Find(c => c.PermissionCode == r);
sys_permissionsNew.Add(tempPermission);
});
return sys_permissionsNew;
the list permissionCodes is a List<string> include 5 string object : '1001','1002','1003','1004','1005' .
the list sys_permissions includes 5 Sys_Permission model objects, the values of the permissionCode are also : '1001','1002','1003','1004','1005' .
the issue is why it returns null when the find() method runs to the last one ?
the find() method can return '1001','1002','1003','1004' . but it returns null when it finds the '1005' ?
so that the sys_permissionsNew only fetch four values without the last one valued '1005' .
who can tell me what's wrong with it ? thanks .
推荐答案
如果您查看文档: ^ ]解释说:
If you look at the documentation: MSDN[^] it explains that:
Return Value
Type: T
The first element that matches the conditions defined by the specified predicate, if found; otherwise, the default value for type T.
...
Important note
When searching a list containing value types, make sure the default value for the type does not satisfy the search predicate. Otherwise, there is no way to distinguish between a default value indicating that no match was found and a list element that happens to have the default value for the type. If the default value satisfies the search predicate, use the FindIndex method instead.
基本上,当匹配用尽时,它将返回默认值-对于引用类型,它是null
Basically, it returns the default value when it runs out of matches - for a reference type, that''s null
谢谢大家.问题解决了.因为数据库中的PermissionCodes的值为"1005",但是在数据库中,"sys_permissions"的值为"1005".
当我将许可代码插入db时,这是我的错.
谢谢原创.
thanks you all . the issue is solved . cause the values of permissionCodes in the database are ''1005 '' , but the value of ''sys_permissions'' is ''1005'' in the databse .
it is my fault when I insert the permission codes into the db .
thanks original .
这篇关于为什么列出. Find()方法将最后一个对象返回为null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文