Home > Back-end >  Distinct and DateTime in c#
Distinct and DateTime in c#

Time:11-26

I have 2 problems. I'm trying to make my first application in xamarin, and i have list of Dates. First problem is format. When i add bind datetime to label it looks like this "25.11.2021 00:00". What i can do to have only date? second problem i have with distinct. A lot of the dates are the same and I want only one unique. I can't use DistincBy, so i write something like this MyList.Select(x => x.dateTime).Distinct().ToList() but that not work. Someone can tell me what I do wrong?

CodePudding user response:

Date part

Use the .Date of DateTimes values, it will give you only the Date. Then use the function .ToString("dd.MM.yyyy") to extract the date in a string that you will be able to us in your label.

Exemple code :

string myDate = DateTime.Now.ToString("dd.MM.yyyy");

Distinct part

For the .Select() problem, also use the .Date in your filter because it will check if dates are the same and not datetime, which contains precise data allowing to have tiny differences between 2 dates.

The code for the .Select() would be :

MyList.Select(x => x.dateTime.Date).Distinct().ToList();
  • Related