• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
翩翩
业精于勤,荒于嬉,行成于思,毁于随
博客园    首页    新随笔    联系   管理    订阅  订阅
今天遇到一个问题,linq语句的写法,查询动态字段
  public List<Location> getLocationList(int companyid, string searchValue, string searchField)
{
...
 var dbLocList = from x in _dbLocList
                            where x.company_id == companyid 
                            and   x的searchField==searchValue //这里要查询的字段是变量
                            select x;           
}
and那一句怎么实现
 
为list加一个扩展方法:
using System.Reflection;

public static class Extension
{
public static List<T> FinData<T>(this List<T> MyDataList, string CName, string CValue)
{
BindingFlags bindingFlags = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static;
PropertyInfo[] propertyInfos = typeof(T).GetProperties(bindingFlags);
List<T> ResultList = new List<T>();
foreach (PropertyInfo propertyInfo in propertyInfos)
{
if (propertyInfo.Name == CName)
{
MyDataList.ForEach(
j =>
{
string re = propertyInfo.GetValue(j, null).ToString();
if (re == CValue)
{
ResultList.Add(j);
}
}
);
}
}
return ResultList;
}
}

上面的问题解决了:

var dbLocList =Extension.FinData(_dbLocList,searchField,searchValue);

 

posted on 2013-10-25 09:35  翩翩  阅读(1816)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3