C# LINQ Dynamic Select with all type of data

孤者浪人 提交于 2019-12-11 12:09:16

问题


I am implementing search by using dynamic LINQ, where the query gets column name and search value in runtime. In this way, I need to parse the data according to the column type-

if (isNumeric)
{
  int x = Int32.Parse(txtHistorySearch.Text);
  truncatedData = ((IQueryable<object>)rawData).Where(columnName + "=@0", x).ToList();
}
else if (DateTime.TryParse(txtHistorySearch.Text, out temp))
{
  var parsedDt = DateTime.Parse(txtHistorySearch.Text);
  var nextDay = parsedDt.AddDays(1);
  truncatedData = ((IQueryable<object>)rawData).Where(columnName + ">= @0 && " + columnName + " < @1", parsedDt, nextDay).ToList();
}
else
{
 truncatedData = ((IQueryable<object>)rawData).Where(columnName + "=@0", searchValue).ToList();
}

Can this be done for all data types using single where clause?


回答1:


You can do this using expression trees.

https://msdn.microsoft.com/en-us/library/bb397951.aspx

https://msdn.microsoft.com/en-us/library/bb882637.aspx



来源:https://stackoverflow.com/questions/31789229/c-sharp-linq-dynamic-select-with-all-type-of-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!