简化将List<DateTime>转换为SortedSet<long>

3

我正在尝试简化下面的解决方案,其中我正在尝试将 List<DateTime> 转换为 SortedSet<long>。我想知道这是否可能?

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));
}

我已经成功通过以下方法将 List<float> 转换为 List<double>:

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

然而,我找不到.ToSet().ToSortedSet()方法。


@John 啊,谢谢。为什么会没有 .ToSortedSet() 的原因是什么? - Jon
仔细观察后发现,在 .NET Framework 中似乎不存在 .ToHashSet() 方法,但在 .NET Core 和 .NET Standard 中存在。这似乎是一个新的添加。也许他们将来会添加更多内容。 - ProgrammingLlama
2
@Jon:为什么没有你想要的功能呢?原因总是相同的:没有人实现那个功能。为了让你使用一个功能,必须有人来实现它。你没有实现它,也没有其他人实现它。为什么你没有实现它呢? - Eric Lippert
@Joker_vD:我不理解你的建议,你能提供这种方法的实现吗? - Eric Lippert
@EricLippert:我不认为这是个好主意,但我猜Joker是在问这样的东西:public static T ToCollection<T,U>(this IEnumerable<U> collection) where T: ICollection<U>, new() {T retval = new T();foreach(U item in collection){retval.Add(item);}return retval;}。我找不到任何不需要调用者显式指定类型参数的实现方法。 - Brian
显示剩余4条评论
1个回答

3
使用接受 IEnumerable<T> 的构造函数重载怎么样?:
timestamps = new SortedSet<long>(dateTimes.Select(convertDateTimeToTimestamp));

或者将其封装在扩展方法中:

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);
        }
    }
}

那么你可以简单地调用dateTimes.Select(convertDateTimeToTimestamp).ToSortedSet();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接