Dynamically search in class fields (each time a different field)

In my Person class, I have fields like firstname, lastname, nickname, etc.

I want to write the search code dynamically, sometimes by the name "firstname", and sometimes by the field "nickname".

In the usual manner, 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, if every time)

Object someVariable  = "firstname";

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

Can anyone know if this is possible?

+3
source share
5 answers

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();
+5
source

You can use another delegate to Where:

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

( , = ==)

+1

You can use reflection:

object someVariable  = "firstname";
var fieldToCheck = person.GetType().GetField(someVariable);
var isEqual = (string)fieldToCheck.GetValue(person) == "MyValue";
+1
source

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

0
source

There is an entry in dynamic sorting in LINQ that can help you, since the principles are similar.

0
source

Source: https://habr.com/ru/post/1742993/


All Articles