[英]Using find method of the list collection
I have a web application in which I use List
collection. 我有一个使用
List
集合的Web应用程序。 I'd like to replace this snippet by another more efficient. 我想用另一个更高效的代码替换该代码段。
List<Project> liste = notre_admin.Get_Project_List();
Project p = new Project();
foreach (Project pi in liste)
{
if (pi.Id_project == id_project) {p = pi; break;}
}
I'd like to replace these lines of code by one line in which i use find
method of the List
. 我想将这些代码行替换为我使用
List
find
方法的一行。
How can I change the snippet ? 如何更改代码段?
You could use Linq
to resolve it. 您可以使用
Linq
来解决它。 First, include the namespace: 首先,包括名称空间:
using System.Linq;
After, try to find the first element using a lambda expression in FirstOrDefault
extension method: 之后,尝试在
FirstOrDefault
扩展方法中使用lambda表达式查找第一个元素:
var item = liste.FirstOrDefault(x => x.Id_project == id_project);
if (item != null)
{
// use the object found
}
You can use LINQ
for that (as Felipe Oriani suggested), or List<T>.Find
method (which won't require additional include
statements): 您可以为此使用
LINQ
(如Felipe Oriani所建议),或使用List<T>.Find
方法(不需要其他include
语句):
List<Project> liste = notre_admin.Get_Project_List();
Project p = liste.Find(x => x.Id_project == id_project);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.