看下面的代码我想用参数字段中接收的字段名替换USERNAME.这种方法必须能够对几个字段进行一些搜索.
谢谢,
public void Searching(string field,string stringToSearch) { var res = from user in _dataContext.USERs where user.USERNAME.Contains(stringToSearch) select new { Id = user.ID,Username = user.USERNAME }; }
解决方法
你需要忘记匿名类型,也许使用Tuple< int,string>代替;但是:怎么样:
IQueryable<Foo> source = // YOUR SOURCE HERE // in-memory dummy example: // source = new[] { // new Foo {Id = 1,Bar = "abc"},// new Foo {Id = 2,Bar = "def"} // }.AsQueryable(); string field = "Bar"; string stringToSearch = "d"; var param = Expression.Parameter(typeof (Foo),"x"); var predicate = Expression.Lambda<Func<Foo,bool>>( Expression.Call( Expression.PropertyOrField(param,field),"Contains",null,Expression.Constant(stringToSearch) ),param); var projection = Expression.Lambda<Func<Foo,Tuple<int,string>>>( Expression.Call(typeof(Tuple),"Create",new[] {typeof(int),typeof(string)},Expression.PropertyOrField(param,"Id"),field)),param); Tuple<int,string>[] data = source.Where(predicate).Select(projection).ToArray();