如何有效地使用enumerable.repeat
本文关键字:enumerable repeat 有效地 | 更新日期: 2023-09-27 18:03:09
我只想在其他代码位置使用此查询初始化:
var post = Enumerable.Repeat(new
{
Id = default(int),
Title = string.Empty,
Publisher = string.Empty,
ToUser = string.Empty,
PublishDate = default(DateTime?),//need to default(DateTime)
IsFile = default(bool),
CategoryName = string.Empty,
status_name = string.Empty,
Group_name = string.Empty,
FileSize = default(long?)
}, 0).ToList();
我声明了一个常见的post查询。现在我只想让PublishDate
变成default(DateTime?)
或者default(DateTime)
。
我可以设置它为空和非空吗?当初始化这个查询时,它需要一个非空的datetime。
------------------------- 更新 --------------------------
这里我需要nullable datetime
post = db.Posts.Where(p => (p.ToUser_id.Equals(user_id) || p.ToUser_id.Equals(null)) && p.User_id != user_id).OrderByDescending(p => p.Sent_Datetime).Select(p => new
{
Id = p.Id,
Title = p.Title,
Publisher = db.Users.Where(u => u.Id.Equals(p.User_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
ToUser = db.Users.Where(u => u.Id.Equals(p.ToUser_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
PublishDate = p.Sent_Datetime,//nullable date time field
IsFile = p.IsFileAttached,
CategoryName = db.Categories.Where(c => c.Id.Equals(p.Category_id)).Select(c => c.Category_name).FirstOrDefault(),
status_name = db.Status.Where(s => s.Id.Equals(p.status_id)).Select(s => s.status_name).FirstOrDefault(),
Group_name = db.Groups.Where(g => g.Id.Equals(p.group_id)).Select(g => g.Group_name).FirstOrDefault(),
FileSize = p.TotalFileSize
}).FilterForColumn(ColumnName, SearchText).ToList();
这里我想要非空的datetime
post = db.Posts.Where(p => p.User_id.Equals(user_id) && p.ToUser_id.Equals(user_id) && p.Sent_Datetime.Equals(null)).OrderByDescending(p => p.Created_datetime).Select(p => new
{
Id = p.Id,
Title = p.Title,
Publisher = db.Users.Where(u => u.Id.Equals(p.User_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
ToUser = db.Users.Where(u => u.Id.Equals(p.ToUser_id)).Select(u => u.First_name + ' ' + u.Last_name).FirstOrDefault(),
PublishDate = p.Created_datetime,//non-nullable date time field
IsFile = p.IsFileAttached,
CategoryName = db.Categories.Where(c => c.Id.Equals(p.Category_id)).Select(c => c.Category_name).FirstOrDefault(),
status_name = db.Status.Where(s => s.Id.Equals(p.status_id)).Select(s => s.status_name).FirstOrDefault(),
Group_name = db.Groups.Where(g => g.Id.Equals(p.group_id)).Select(g => g.Group_name).FirstOrDefault(),
FileSize = p.TotalFileSize
}).FilterForColumn(ColumnName, SearchText).ToList();
您可以将其强制转换为Nullable<DateTime>
:
PublishDate = (DateTime?)default(DateTime),
例如一个匿名类型的列表:
var post = Enumerable.Repeat(new
{
Id = default(int),
Title = string.Empty,
Publisher = string.Empty,
ToUser = string.Empty,
PublishDate = (DateTime?)default(DateTime),
IsFile = default(bool),
CategoryName = string.Empty,
status_name = string.Empty,
Group_name = string.Empty,
FileSize = default(long?)
}, 1).ToList();
这里PublishDate
是01.01.0001 00:00:00
而不是null
。