开发者

Search dynamically in fields of class(each time by other field)

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?


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();


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 ==)


You could use reflection:

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


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜