从列表中
class Delivery
{
public string ProductCode
{
get;
set;
}
public DateTime? OrderedDate
{
get;
set;
}
public DateTime? DeliveryDate
{
get;
set;
}
public Delivery(string pcode, DateTime? orddate, DateTime? deldate)
{
ProductCode = pcode;
OrderedDate = orddate;
DeliveryDate = deldate;
}
}
List<Delivery> DeliveryList = new List<Delivery>();
DeliveryList.Add(new Delivery("P001",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P007",new DateTime(2009,05,17),null));
DeliveryList.Add(new Delivery("P031", new DateTime(2008, 03, 15),
new DateTime(2008,04 ,22)));
DeliveryList.Add(new Delivery("P011",new DateTime(2009,01,27),
new DateTime(2009,02,12)));
DeliveryList.Add(new Delivery("P041",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P051", new DateTime(2009, 01, 27),
new DateTime(2009, 02, 12)));
DeliveryList.Add(new Delivery("P501",new DateTime(2009,01,27),null));
DeliveryList.Add(new Delivery("P801",new DateTime(2009,01,27),null));
var query = DeliveryList.OrderBy(p => p.DeliveryDate);
出于报告目的,在LINQ执行期间,用什么方法替换空值(基于交付日期) 消息“尚未交付”(DateTime是值类型)。
答案 0 :(得分:7)
var result = DeliveryList.Select(x => new
{
ProductCode = x.ProductCode,
OrderedDate = x.OrderedDate,
DeliveryDate = x.DeliveryDate.HasValue
? x.DeliveryDate.Value.ToString() : "Yet to be delivered"
}).OrderBy(p => p.DeliveryDate).ToArray();
答案 1 :(得分:3)
我不是100%肯定你的要求,但听起来你想将DeliverList转换成一个字符串集合,表明它们何时被交付。如果您希望字符串“尚未交付”,则为null DeliveryDate。如果是这样,请尝试以下方法。
var dates = DeliveryList
.Select(x => x.DeliverDate
? x.DeliverDate.Value.ToString
: "Yet to be delivered");
答案 2 :(得分:0)
如果您希望保持类型与上面的解决方案一样,则会创建一个匿名类型,并且交付日期可能会以字符串形式结束。
List<Delivery> query = (from d in DeliveryList
select new Delivery
(
d.ProductCode,
d.OrderedDate,
d.DeliveryDate ?? DateTime.Now
)).OrderBy(p=>p.DeliveryDate).ToList();
如果您的Delivery类中有一个空构造函数,则可以执行类似
的操作List<Delivery> query2 = (from d in DeliveryList
select new Delivery
{
DeliveryDate = d.DeliveryDate ?? DateTime.Now,
OrderedDate = d.OrderedDate,
ProductCode = d.ProductCode
}).OrderBy(p=>p.DeliveryDate).ToList();
如果它是空的,那么你必须做的一件事就是对你的DeliveryDate进行有意义的替换。我不认为DateTime.Now会有用,现在你会遇到DateTime字段。显而易见的优点是,您正与一个强烈投射的List对象坐在一起。并且有助于我猜你以后是否会将逻辑放入你的构造函数中。