在我的’Person’课程中,我有一些字段,如’firstname’,’lastname’,’nickname’等等. 我想编写动态搜索的代码,有时候是’firstname’,有时是’nickname’字段. 以常规方式,代码将是: If(Search
我想编写动态搜索的代码,有时候是’firstname’,有时是’nickname’字段.
以常规方式,代码将是:
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(); }
但是我想写的代码应该是这样的:(每次保存if)
Object someVariable = "firstname"; Person result = ListOfPerson.Where(p => p.someVariable == "exp").FirstOrDefault();
任何人都可以知道它是否可能?
这样的事情怎么样: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();