2009-12-03 35 views
3

更换空从列表C#LINQ有意义的字符串

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是值类型)。

回答

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

@Darin没有ToArray()也代码为我工作,是否有必要包括ToArray()? – user215675 2009-12-03 07:35:32

+0

ToArray非常重要。没有它,结果将是每次尝试使用它时重新执行的查询。这可能会导致巨大的性能损失,具体取决于您如何使用它。 – 2009-12-03 07:42:28

3

我不是100%确定你的要求,但它听起来像你想将DeliverList转换成指示它们何时交付的字符串集合。尽管您希望字符串“尚未交付”,但为空DeliveryDate。如果是这样,尝试以下。

var dates = DeliveryList 
    .Select(x => x.DeliverDate 
    ? x.DeliverDate.Value.ToString 
    : "Yet to be delivered"); 
+0

Jared:谓词x.DeliverDate是否返回true,如果不为null?如果是这样,酷,这是很少“!=空”键入!谢谢! – 2009-12-03 07:29:47

+0

感谢JaredPar和Darin – user215675 2009-12-03 07:33:54

0

Darin的解决方案是整洁,我会去用它。作为替代考虑因素......

如果您想保留上述解决方案的类型,则会创建一个匿名类型,并且交付日期最终可能会以字符串结尾。

List<Delivery> query = (from d in DeliveryList 
         select new Delivery 
         (
           d.ProductCode, 
           d.OrderedDate, 
           d.DeliveryDate ?? DateTime.Now 
         )).OrderBy(p=>p.DeliveryDate).ToList(); 

如果您在交货类有一个空的构造函数,你可以做类似

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一个meaninful更换,如果是空值。我不认为DateTime.Now会有用,现在你会被卡住DateTime字段。显然,优势在于你坐在一个强力施展的List对象上。如果后来你确实会把逻辑放到你的构造器中,那么我猜可以帮助你。