3

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?

yossharel
  • 1,819
  • 2
  • 23
  • 29

5 Answers5

5

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
  • 21,302
  • 14
  • 69
  • 94
1

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
  • 45,220
  • 19
  • 132
  • 189
  • 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 Apr 27 '10 at 14:06
1

You could use reflection:

object someVariable  = "firstname";
var fieldToCheck = person.GetType().GetField(someVariable);
var isEqual = (string)fieldToCheck.GetValue(person) == "MyValue";
Daniel Rose
  • 17,233
  • 9
  • 65
  • 88
0

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

cortijon
  • 983
  • 6
  • 13
0

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

Community
  • 1
  • 1
Dan Diplo
  • 25,076
  • 4
  • 67
  • 89