Let's say we have an object called Person with public properties PersonID, Name, Age, Gender as defined below.
using System.Collections.Generic.List;
public class Person
{
public int PersonID {get; set;}
public string Name {get; set;}
public int Age {get; set;}
public bool Gender {get; set;}
}
class program
{
public static void Main(string[] args)
{
// Let's say we have a method defined as dbAccess.GetPersons() to
//return all the records from Person table and populates the
//list object "persons" as shown below.
List
int personIDToFind = 1234;
//Find person in persons list by PersonID using predicate
//"p=>p.PersonID == personIDToFind"
Person personByFindOperation = persons.Find( p=>p.PersonID == personIDToFind );
string personName = "Kiran"
//Find person in persons list by Name using predicate
//"p=>p.Name == personName"
Person personByFindOperation2 = persons.Find( p=>p.Name == personName );
}
}
Note: The Find method of List returns the first occurrence of the exact match within the entire System.Collections.Generic.List.
3 comments:
I would also mention the .SingleOrDefault(p => p.Name == personName)
:)
Hi Kiran,
How would you select the youngest or oldest person from the list?
var maxAge = persons.Max(l => l.Age);
Person oldestPerson = (from p in persons
where p.Age == maxAge
select p).FirstOrDefault;
var minAge = persons.Min(l => l.Age);
Person youngestPerson = (from p in persons
where p.Age == minAge
select p).FirstOrDefault;
Post a Comment