0

i have a list of objects and i want to create a list of attributes of those objects. The following works:

List<string> dates = objectlist.Select(d => d.date).ToList();

The date is stored as string in a strange format, so i just want to first 12 chars and tried this:

List<string> dates = objectlist.Select(d => d.date.Substring(0,12)).ToList();

this fails with a hint that there is no existing object instance... I do not know what is the problem here but i want to avoid going to the list a second time.

What is the best way to achieve what i want?

Oliver
  • 149
  • 8
  • Is it `d.date` a `DateTime Object`? – Nekeniehl Mar 04 '19 at 13:20
  • 1
    Looks like some of your `date` is null. Try `d.date?.Substring(0,12)` and then filter null values – Aleks Andreev Mar 04 '19 at 13:23
  • 2
    `Substring()` indicate that `d.date`is a string. String can be `null`. but `null` doens't has a method `Substring()`. what do you expect from a null Date? Do you want an empty string as result of the substring ? Do you want to filter them before? Do you want an error? – Drag and Drop Mar 04 '19 at 13:23
  • Yes you are right, there was a null-string. I will keep the Null-Conditional-Operator. And also the values are datetimes but stored as strings. – Oliver Mar 04 '19 at 13:30
  • 1
    So what should happen on a date which is `null`: `null.SubString(0, 12)` won´t work, as you´ve already noticed, so what should happen? – HimBromBeere Mar 04 '19 at 13:31
  • 1
    var dates = objectlist.Where(x => x.Date?.Length >= 12) .Select(d => d.Date.Substring(0, 12)).ToList(); – Yauhen Sampir Mar 04 '19 at 13:33

0 Answers0