开发者

Best way to get individual days from a column, using LINQ

I have the following data in one MSSQL Table column

2011-06-20 11:53:32.000
2011-06-20 11:54:24.000
2011-06-20 11:55:45.000
2011-08-05 10:24:12.000
2011-08-05 10:25:28.000
2011-08-05 10:26:20.000
2011-08-05 10:27:12.000
201开发者_如何学运维1-08-05 10:28:04.000
2011-08-05 10:28:55.000

Using LINQ, I would like to get the following data from the column

2011-06-20 
2011-08-05

So I can put into a List<>

What's the best way to do this? I already have the context stuff setup, so I don't need details on that. I just need an idea of the best "query" and logic I can use to get this data. Thanks!


You are looking for all of the Distinct dates in a range of DateTimes, the following will show examples to get what you need, given you already have them in a string or by querying your database:

Example (with list of strings):

var list; //Contains your dates
var result = list.Select(x => x.Date.ToShortDateString()).Distinct();

Example (from database table):

List<String> dates = (FROM d in datesTable
                      SELECT d.date.ToShortDateString()).Distinct().ToList();

Console Example to demonstrate functionality:

List<DateTime> list = new List<DateTime>();
list.Add(DateTime.Parse("2011-06-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:53:32.000"));
list.Add(DateTime.Parse("2011-05-20 11:44:32.000"));
list.Add(DateTime.Parse("2011-04-20 11:53:32.000"));

var result = list.Select(x => x.Date.ToShortDateString()).Distinct();

foreach (string date in result)
{
    Console.WriteLine(date);
}
Console.Read();


var q = from t in mydates select distinct ( t.Date.ToShortDateString());


To select distinct dates into a list try this:

List<String> myDates = (from t in myTable
                        select t.myDate.ToShortDateString()
                       ).Distinct().ToList()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜