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,709
  • 2
  • 22
  • 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
  • 20,290
  • 14
  • 66
  • 90
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
  • 42,842
  • 15
  • 122
  • 181
  • 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
  • 16,331
  • 9
  • 59
  • 81
0

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

cortijon
  • 963
  • 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
  • 24,377
  • 4
  • 61
  • 86