Search code examples
c#linqlinq-to-entities

Linq: add objects from one list to another with an other type, (MVC, C#)


I have a "FindItemsResults<Appointment> list" which contains appointment objects.

I want to select "Start" property value and of all appointment objects from this List and save these values in an other list of type DateTime ... List<DateTime> avaliableBookingDays

List<DateTime> avaliableBookingDays = new List<DateTime>();
FindItemsResults<Appointment> appointments = calendar.FindAppointments(cView);
IEnumerable<DateTime> res = from x in appointments
                            select new DateTime { (x.Start};
avaliableBookingDays.AddRange(res);

My LINQ exepression fails:

IEnumerable<DateTime> res = from x in appointments
                          select new DateTime { (x.Start};

I get error, like that:

Cannot inittialize type "DateTime" with a collection inittializer because it do not implement "System.Collections.IEnumerable"

The above-mentioned LINQ must do this:

foreach (var appObj in appointments)
{
    avaliableBookingDays.Add(appObj.Start);
}

Solution

  • Your code is not even going to compile

    IEnumerable<DateTime> res = from x in appointments
                              select new DateTime { (x.Start};
    

    because it has syntax errors ! In your select part, you are projecting to a new DateTime object and you have just an opening ( , which does not make any sense!

    I think you were getting the mentioned error when you had the closing bracket as well like

    IEnumerable<DateTime> res = from x in appointments
                              select new DateTime { (x.Start)};
    

    Here your code is trying (assume it was valid) to project the items from appointments collection to another collection of DateTime with some invalid syntax ! There is no need to use the new keyword here as you are not trying to create an object of a view model class/annonymous object since all you need is the Start property value.

    Solution

    Since Start is the DateTime type property, you want to select only that.

    List<DateTime> avaliableBookingDays = (from x in appointments 
                                                  select x.Start).ToList();
    

    Or

    List<DateTime> avaliableBookingDays = appointments.Select(a=>a.Start).ToList();