Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# LINQ replacing nulls with meaningful string

Tags:

c#

linq

From the list

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);

For Report purpose ,During LINQ execution,What is the way to replace null values (Based on Delivery Date) with message "Yet to be delivered" (DateTime is value type).

like image 325
user215675 Avatar asked Dec 07 '25 10:12

user215675


2 Answers

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();
like image 188
Darin Dimitrov Avatar answered Dec 10 '25 21:12

Darin Dimitrov


I'm not 100% sure what your asking but it sounds like you want to convert DeliverList into a collection of strings indicating when they were delivered. In the case of a null DeliveryDate though you want the string "Yet to be delivered". If so try the following.

var dates = DeliveryList
  .Select(x => x.DeliverDate 
     ? x.DeliverDate.Value.ToString 
     : "Yet to be delivered");
like image 45
JaredPar Avatar answered Dec 10 '25 19:12

JaredPar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!