如何使用Linq进行搜索时使用日期。我想我在宣言上遗漏了一些东西
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where ((va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
答案 0 :(得分:0)
可能是拼写错误,但您需要将 searchDateFrom / searchDateTo 转换为DateTime,并且您的linq语句中还有两个额外的括号
答案 1 :(得分:0)
这是我设置单元测试以查看正在发生的事情。
检查括号并从字符串转换为日期时间:
[TestMethod]
public void TestMethod1()
{
List<myTable> myTables = new List<myTable>();
for (int month = 1; month < 10; month++)
{
for (int day = 1; day < 20; day++)
{
myTables.Add(new myTable { PersonName = "Person " + month.ToString() + " " + day.ToString(), ApplicationReceivedDate = new DateTime(2011, month, day) });
}
}
string searchName = "Person";
DateTime searchDateFrom = Convert.ToDateTime("2011-01-02");
DateTime searchDateTo = Convert.ToDateTime("2011-01-03");
var Results = (from va in myTables
where va.PersonName.Contains(searchName)
&& va.ApplicationReceivedDate >= searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo
select va);
Assert.AreEqual(Results.Count(), 1);
}
public class myTable
{
public string PersonName { get; set; }
public DateTime ApplicationReceivedDate { get; set; }
}
同时检查&amp;到。
答案 2 :(得分:0)
我还建议使用更干净的缩进,更容易理解和计算括号和内容。
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
答案 3 :(得分:0)
HttpRequest.Form是NameValueCollection,您可以通过int / string索引器在其中获取字符串。也就是说,Request.Form["ReceivedDateFrom"]
返回一个字符串,您无法将其分配给类型为DateTime
且没有任何转换的变量。您可以尝试使用DateTime.ParseExact方法将字符串转换为DateTime
。但是,如果您不能保证字符串格式正确,则可以使用TryParse方法。