0

I have a situation where I want to convert a row of data that spans multiple days into multiple objects.

namespace Linq
{
    class Program
    {
        static void Main(string[] args)
        {
            var item = new List<Item>
            {
                new Item {StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(2)},
                new Item {StartDate = DateTime.Now, EndDate = DateTime.Now.AddMinutes(120)}
            };
        }
    }
}

public class Item
{
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

For the output I would like this:

As the first row spans two days I want two rows for Row1

Row1, 21/04/2016
Row1, 22/04/2016
Row2, 21/04/2016

Hope this makes sense?

Ɖiamond ǤeezeƦ
  • 3,223
  • 3
  • 28
  • 40

2 Answers2

0

You could try override Item.ToString().

e.g.

public override string ToString()
{
    var endDateStr = StartDate.Date != EndDate.Date 
        ? Environment.NewLine + EndDate.ToShortDateString() 
        : string.Empty;
    return string.Format("{0}{1}", StartDate.ToShortDateString(), endDateStr);
}

Check here

0

You can use the Linq query outlined in Create an array or List of all dates between two dates.

var results = items.SelectMany(i => 
       Enumerable.Range(0, 1 + i.EndDate.Subtract(i.StartDate).Days)
      .Select(offset => new { id = i.id, date = i.StartDate.AddDays(offset).Date})
      .ToArray());

To make this work, I edited the definition of Item to be as follows:

public class Item
{
    public int id;
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
}

You can see it in action at https://dotnetfiddle.net/XIfMmr . Note that the result is slightly different than what you desired, as DateTime.Now.AddDays(2) will always span 3 days.

Community
  • 1
  • 1
gnalck
  • 972
  • 6
  • 12