C# Linq SortedList 过滤到 SortedList
我有一些代码,其中我正在做一些奇怪的事情来从 SortedList 中获取信息并返回到另一个 SortedList 中。我执行 where 子句,然后必须将所有 KeyValuePair 单独放回到新的 SortedList 中。
这不可能是最有效的,或者实际上是推荐的方法,但我似乎找不到更好的方法。
这是代码:
SortedList<DateTime, CalendarDay> most_days =
new SortedList<DateTime, CalendarDay>();
List<KeyValuePair<DateTime, CalendarDay>> days = this.all_days.Where (
n => n.Value.IsRequested || n.Value.IsApproved
).ToList();
foreach (KeyValuePair<DateTime, CalendarDay> kvp in days)
most_days.Add(kvp.Key, kvp.Value);
关于如何清理它的任何想法(正如他们所说,少即是多)?
谢谢,
乔纳森
I have got some code in which I am doing some weirdness to get information out of a SortedList and back into another SortedList. I do my where clause, then have to individually put all the KeyValuePairs back into a new SortedList.
This can't be the most efficient, or indeed the recommended, way of doing this, but I can't seem to find a better way.
Here is the code:
SortedList<DateTime, CalendarDay> most_days =
new SortedList<DateTime, CalendarDay>();
List<KeyValuePair<DateTime, CalendarDay>> days = this.all_days.Where (
n => n.Value.IsRequested || n.Value.IsApproved
).ToList();
foreach (KeyValuePair<DateTime, CalendarDay> kvp in days)
most_days.Add(kvp.Key, kvp.Value);
Any ideas on how I can clean this up (less is more, as they say)?
Thanks,
Jonathan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好吧,您当然可以删除
ToList
调用 - 这对您没有任何帮助。您可以使调用代码更简单,如下所示:
...但这将构建一个中间
Dictionary<,>
,因此效率很低。另一种选择是您可以编写自己的
ToSortedList
扩展方法,例如然后调用代码将是:
我怀疑这应该相当有效,因为它总是会向 end 添加值构建期间列表的。
(对于完整的工作,您需要添加接受自定义键比较器等的重载......请参阅
ToDictionary
。)Well you could certainly remove the
ToList
call - that's not helping you at all.You could make the calling code simpler like this:
... but that's going to build an intermediate
Dictionary<,>
, so it's hardly efficient.Another option is that you could write your own
ToSortedList
extension method, e.g.Then the calling code will just be:
I suspect this should be reasonably efficient, as it will always be adding values to the end of the list during construction.
(For a complete job you'd want to add overloads accepting custom key comparers etc... see
ToDictionary
.)不是对您的问题的直接答案(抱歉!) - 更多关于这个问题的问题:
SortedList
吗?IEnumerable
且结果顺序正确的情况下生存?如果您在创建
mostDays
集合后从未打算向其添加/插入更多项目,那么您显然可以使用varmostDays = allDays 创建一个
IEnumerable
.Where(n => n.Value.IsRequested || n.Value.IsApproved);Not a direct answer to your question (sorry!) - more a question on the question:
SortedList
?IEnumerable
where the results happen to be in the right order?If you never intend to add/insert more items to
mostDays
collection after you've created it, then you could obviously just create anIEnumerable
usingvar mostDays = allDays.Where(n => n.Value.IsRequested || n.Value.IsApproved);