简体   繁体   中英

Using find method of the list collection

I have a web application in which I use List collection. 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 .

How can I change the snippet ?

You could use Linq to resolve it. First, include the namespace:

using System.Linq;

After, try to find the first element using a lambda expression in FirstOrDefault extension method:

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):

List<Project> liste = notre_admin.Get_Project_List();
Project p = liste.Find(x => x.Id_project == id_project);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM