N
N
neitoo2021-11-24 18:01:30
C++ / C#
neitoo, 2021-11-24 18:01:30

How to output dates from a list where dd=20?

I need to display all dates where the day of the month = 20, I don’t understand how this can be done ... (with or without split)

static void Main(string[] args)
        {
            List<string> date = new List<string>()
            {
                "20.11.2021",
                "10.11.2020",
                "18.08.2017",
                "20.05.2019",
                "06.10.2013"
            };
            
            for (int i = 0; i < date.Count; i++)
            {
                Console.WriteLine(date[i]);
            }
        }


PS I'm just learning, so I don't rule out that the code can be terrible :(

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2021-11-24
@neitoo

Option 1, with date parsing:

var dates = new[] {
                "20.11.2021",
                "10.11.2020",
                "18.08.2017",
                "20.05.2019",
                "06.10.2013"
};
var lateDates = from date in dates 
                let value = DateOnly.ParseExact(date, "dd.MM.yyyy") // DateOnly добавили в .net6, но можно спокойно вместо него использовать DateTime
                where value.Day == 20
                select value; // вместо value можно выьрать date
                
foreach(var d in lateDates) 
  Console.WriteLine(d);

Option 2, via split:
var dates = new[] {
                "20.11.2021",
                "10.11.2020",
                "18.08.2017",
                "20.05.2019",
                "06.10.2013"
};
var lateDates = from date in dates
                let dayPart = date.Split(".", 2)[0]
                let dayOfMonth = int.Parse(dayPart) // тут можно тупо без парсинга сделать where dayPart == "20"
                where dayOfMonth == 20
                select date;
foreach (var d in lateDates)
    Console.WriteLine(d);

In both cases, TryParse can be used instead of parse to handle the error normally, but then the code will be a little more complicated.
3. Another fun option, especially for this task.
You can stupidly check that the string starts with 20
var data = dates.Where(x => x.StartsWith("20."));
foreach(var d in data)
  Console.WriteLine(d);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question