tags:

views:

129

answers:

5

hi all,

In my 'Person' class, I have some fields like 'firstname','lastname','nickname' and so on.

I want to write code to search dynamically, sometimes by 'firstname' and sometimes by 'nickname' field.

In the regular way, the code will be:

If(SearchBy == "firstname") 
{
     Person result = ListOfPerson.Where(p => p.firstname== "exp").FirstOrDefault();
}
else If(SearchBy == "nickname") 
{
      Person result = ListOfPerson.Where(p => p.nickname== "exp").FirstOrDefault();
}

But the code I want to write, should be like this:(to save the if each time)

Object someVariable  = "firstname";

Person result = ListOfPerson.Where(p => p.someVariable == "exp").FirstOrDefault();

Can anyone Know if it's possible?

+1  A: 

You can use a different delegate for the Where:

Person findFirstname = ListOfPerson.Where(p => p.firstname == "exp").FirstOrDefault();
// or
Person findLastname = ListOfPerson.Where(p => p.lastname == "exp").FirstOrDefault();

(note I've changed = to ==)

thecoop
thanks about the correction.I want to save code. insted 'if' or 'case'- I want to hold the field to search by in any variable. I'm not sure that is possible
yossharel
+5  A: 

How about something like this:

Func<Person, bool> searchDelegate;

switch (searchMode){
    case "firstname":
        searchDelegate = (p => p.firstname == searchValue);
        break;
    case "lastname":
        searchDelegate = (p => p.lastname == searchValue);
        break;
    case "nickname":
        searchDelegate = (p => p.nickname == searchValue);
        break;
    default:
        throw new Exception("searchMode is invalid");
}

return ListOFPerson.Where(seachDelegate).FirstOrDefault();
MiffTheFox
A: 

LINQ to Objects was developed for just this use: http://msdn.microsoft.com/en-us/library/bb397937.aspx

MrGumbe
+1  A: 

You could use reflection:

object someVariable  = "firstname";
var fieldToCheck = person.GetType().GetField(someVariable);
var isEqual = (string)fieldToCheck.GetValue(person) == "MyValue";
Daniel Rose
A: 

There's a post on dynamic sorting in LINQ that might help you, as the principles are similar.

Dan Diplo