C#Linq Dynamic Select与所有类型的数据[英] C# LINQ Dynamic Select with all type of data

本文是小编为大家收集整理的关于C#Linq Dynamic Select与所有类型的数据的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我正在通过使用Dynamic Linq来实现搜索,其中查询在运行时获取列名和搜索值.这样,我需要根据列类型 -

解析数据
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();
}

可以使用单个子句对所有数据类型进行操作?

推荐答案

您可以使用表达式树进行此操作.

BB397951.aspx

BB882637.aspx

本文地址:https://www.itbaoku.cn/post/1556945.html

问题描述

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?

推荐答案

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