Click here to Skip to main content
15,893,266 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi all,
I have structure as below:
how to find item in list with type is structure?
(don't use For loop)

C#
struct person{
 public int age;
 public string name;
}

public list<person> lstPerson;
public void getListPerson(){
    lstPerson = new list<person>();
    lstperson.Add(New person{age = 10, name="John"});
    lstperson.Add(New person{age = 20, name="John1"});
    lstperson.Add(New person{age = 30, name="John2"});
    lstperson.Add(New person{age = 40, name="John3"});
    lstperson.Add(New person{age = 50, name="John4"});
    lstperson.Add(New person{age = 60, name="John5"});
    lstperson.Add(New person{age = 70, name="John6"});
}

public person searchPerson(string name){
  // how to find person with name is John3 in lstPerson?(don't use loop: For or While)
}
Posted
Comments
Tomas Takac 17-Jun-15 3:53am    
We don't do your homework.

Try:
C#
person p = lstPerson.Where(p => p.name == "John3").FirstOrDefault();
if (p != null)
   {
   ...
   }


[edit]
That works for classes, not structs - sorry, I didn't notice.
C#
List<person> matches = lstPerson.Where(p => p.name == "John3").ToList();
if (matches.Count >= 1)
   {
   person p = matches[0];
   ...
   }

[.edit]
 
Share this answer
 
v2
C#
public person searchPerson(string name)
       {
           var objPers = lstPerson.Where(_ => _.name == name).FirstOrDefault();
           return objPers;
       }
 
Share this answer
 
C#
public person searchPerson(string name){
   person _person = lstPerson.Where(x => x.name == name).FirstOrDefault();
   return _person;
}
 
Share this answer
 
C#
  public  IEnumerable<person> searchPerson(person abc)
   {


IEnumerable<person> p = lstPerson.Where(x => x.name == abc.name || x.age==abc.age);
return p;
   }
 
Share this answer
 
v2
how to search dynamic field in list?
ex: search base on age, or any field if this structure have many feild
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900