views:

119

answers:

2

I have the following problem: in a database table are Sales recorded. One of the field is the SaleDate which is a SQL Server Date type. The Website now allows to search in this field. And it allows to search only for the year.

Let's assume there is one record with the date 2008/11/01. If I search for "2008" the entry is returned, which is of course correct. But searching for "2008/11/01" will not return the entry.

So here's my code:

filteredSales = filteredSales.Where(s => s.SaleDate.ToString().Contains(searchterm));

I have also tried this ones:
filteredSales = filteredSales.Where(s => s.SaleDate.Value.ToString().Contains(searchterm));
filteredSales = filteredSales.Where(s => s.SaleDate.Value.ToShortDateString().Contains(searchterm));

They also don't work.

Maybe this isn't a LinQ problem at all but more of the culture since this is an german application and the search term is really "01.11.2008". But when I output the value from the database or even look directly at the database it's displayed at "01.11.2008".

Thanks for help.

Michael

Here's the complete solution based on the selected answer below:

try
{
    DateTime sdt = DateTime.Parse(suchbegriff, new System.Globalization.CultureInfo("de-DE"));
    filteredSales = filteredSales.Where(s => s.SaleDate.Value == sdt);
}
catch (FormatException e)
{
    // in case we have only the year try to make a string match
    filteredSales = filteredSales.Where(s => s.SaleDate.Value.Year.ToString().Equals(suchbegriff));
}

Michael

+1  A: 

Have you tried something like

s => s.SalesDate == Date.Parse("01 November 2008")

or

s => s.SalesDate == Date.Parse(MyDate)

or

s => s.SalesDate.Year == "2008"

Above is untested. Especially the last one but essentially you want to test the year agains either a number or a year.

I don't think I would ever use contains in a query that involved a date field.

griegs
+1  A: 

Make the comparison using a DateTime object, not with strings for example:

// Parse the search term string to DateTime, using the german culture
DateTime date = DateTime.Parse(searchTerm, new CultureInfo("de-DE"));

var sales = filteredSales.Where(s => s.SaleDate == date);
CMS