Home > Software engineering >  How To Retrieve Group Of Elements From IEnumerable Without Iterating
How To Retrieve Group Of Elements From IEnumerable Without Iterating

Time:11-18

I have the following:

IEnumerable<Personel> personel= page.Retrieve<Personel>....

Then I have List which contains only personelIDs

List<int> personelIDs....

I need to retrived all 'personels' from the IEnumerable and assign it into a new List which matches the personelIDs from 'personelIDs ' list.

I can do it my iterating and having verify the IDs and if they're equal assign it into another List, but is there a short here where I can retrieve it without iterating or having multiple lines of code?

Basically Is there a way on how to shortened this 

List<int> pIds = ....// contains only specific personellID's
IEnumerable personelIEn = // contains Personel data like personel IDs, name..etc

        List<Personel> personel = personelIEn.ToList();
        List<Personel> personelByTag = new List<Personel>();
        foreach (Personel b in personel ) {
            if (pIds.Contains(b.DocumentID)) {
                personelByTag .Add(b);
            }
        }
       
        return personelByTag ;

basically I'm trying to find ways how to shortened the above code

CodePudding user response:

You can use a predicate:

public List<Personel> search(String documentId, List<Personel> list)
{
   Predicate<Personel> predicate = (Personel personel) => (personel.Id== documentId);

   return list.FindAll(predicate);
}

Could that help?

  • Related