简体   繁体   中英

How can I check if the same Date is already in a List?

I have a List of DateTimes (with Times and Dates) and now need a mothod to get all the unique days out of it into a seperate List
Example:

[1.1.2015 12:34]    [1.1.2015 12:34]   [1.1.2015 12:34]
[1.2.2015 4:34]     [1.2.2015 2:34]     [1.2.2015 1:34]
[1.3.2015 8:34]     [1.3.2015 1:34]     [1.6.2015 2:34]  

Needs to be Turned into:

[1.1.2015 0:0]    [1.2.2015 0:0]    [1.3.2015 0:0]    [1.6.2015 0:0]

How Do I do this?

DateTime.Date and Enumrable.Distinct is an option (assuming you don't need to keep order):

var dates = dateAndTimes.Select(d => d.Date).Distinct().ToList();

Distinct may, but does not have to preserve order of items (I believe current implementations will keep order).

If you need to formally guarantee original order - either re-sort ( OrderBy ) if list is already sorted, or iterate items in the original list and add to new list once that are not already in the list (similar to what Distinct does internally, but with guaranteed behavior of your code).

Note that as per Tim Schmelter comment for keeping order of items using something like newList.Contains(itemAboutToBeAdded) is very slow (and awkward as you'd need to check if item is in sequence that is currently being constructed), using regular foreach similar to following would math O(n) performance provided by Distinct along with formal order guarantee:

 var dates = dateAndTimes.Select(d => d.Date);
 var alreadyInList = new HashSet<DateTime>();
 var datesInSameOrder = new List<DateTime>();
 foreach(var date in dates)
 {
    if (!alreadyInList.Contains(date))
    {
        alreadyInList.Add(date);
        datesInSameOrder.Add(date);
    }
 }

Shorter version can be written to rely on the fact that HashSet.Add returns false if item is already present:

var alreadyInList = new HashSet<DateTime>();
var datesInSameOrder = dates.Where(date => alreadyInList.Add(date)).ToList();

or even if relying on implementation details for order of items in HashSet to be the same as order of Add calls (formally order is not defined, so use at own risk, Distinct have the same behavior - so no benefit):

 var datesInSameOrder = new HashSet<DateTime>(dates).ToList();

You can group them on Date property and project all keys:

var dates = dateandTimes.GroupBy(x=> x.Date)
                        .Select(x=>x.Key).ToList();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM