Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq search by differents values

Tags:

c#

linq

I have a class like this:

class Person
{
    private String sName;
    private String sPhone;
    private String sAge;
    private String sE_Mail;
    // … code …
}

And I have to make a search by the value received from the user, it could be, any attribute of this class. I have this too:

public IEnumerable<Person> SearchByPhone(string value)
{
    return from person in personCollection                   
           where person.**SPhone** == value
           select person;
}

I have four methods like this, the only difference is the attribute. Please, can anybody tell me how can I do this in just one method or isn't possible? Thanks.

like image 392
Priscila Avatar asked Mar 29 '13 18:03

Priscila


1 Answers

No need to write separate methods. A single method would be enough:

public IEnumerable<Person> Search<T>(T value, Func<Person,T> mapFunc)
{
    return from person in personCollection                   
           where mapFunc(person).Equals(value)
           select person;
 }

Then call it this way:

Search("SOME VALUE", input=>input.sPhone);  //sPhone must be public
Search("SOME VALUE", input=>input.sAge);     //sAge must be public
like image 104
Hossein Narimani Rad Avatar answered Oct 03 '22 15:10

Hossein Narimani Rad