Simplify Converting List<DateTime> to SortedSet<long>

Viewed 110

I am trying to simplify my solution below where I am trying to convert a List<DateTime> to SortedSet<long>. I am wondering if this is even possible?

List<DateTime> dateTimes = new List<DateTime>();
dateTimes.Add(...);    

// simplify the 5 lines below into 1 line
SortedSet<long> timestamps = new SortedSet<long>();
foreach(DateTime dateTime in dateTimes)
{
    timestamps.Add(convertDateTimeToTimestamp(dateTime));
}

I have been able to convert a List<float> to List<double> via:

List<float> average = new List<float>();
average.Add(...);
List<double> newAverage = average.Select(x => (double?)x).ToList();

I however was unable to find a .ToSet() or .ToSortedSet() method.

1 Answers

What about using the constructor overload that takes IEnumerable<T>?:

timestamps = new SortedSet<long>(dateTimes.Select(convertDateTimeToTimestamp));

Or wrapping it up in an extension method:

namespace System.Linq
{
    public static class CustomLinqExtensions
    {
        public static SortedSet<TSource> ToSortedSet<TSource>(this IEnumerable<TSource> source)
        {
            if (source == null) throw new ArgumentNullException(nameof(source));
            return new SortedSet<TSource>(source);
        }

        public static SortedSet<TSource> ToSortedSet<TSource>(this IEnumerable<TSource> source, IComparer<TSource> comparer)
        {
            if (source == null) throw new ArgumentNullException(nameof(source));
            return new SortedSet<TSource>(source, comparer);
        }
    }
}

Then you can simply call dateTimes.Select(convertDateTimeToTimestamp).ToSortedSet();

Related