问题
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