首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SortedList和Linq

SortedList和Linq
EN

Stack Overflow用户
提问于 2017-05-09 13:47:43
回答 3查看 1.3K关注 0票数 0

在阅读了关于在SortedList中使用Linq时所期望的内容的文档之后,我感到很困惑。

https://msdn.microsoft.com/en-us/library/ms132319(v=vs.110).aspx

我想枚举肯定是按索引排序和检索的,但是值和键呢?这些案子都安全吗?

代码语言:javascript
复制
        var list = new SortedList<DateTime, object>();

        //add entries here ...

        var firstValue1 = list.Values[0];
        var firstValue2 = list.First().Value;
        var firstValue3 = list.Values.First();

        var firstKey1 = list.Keys[list.Count-1];
        var firstKey2 = list.First().Key;
        var firstKey3 = list.Keys.First();

        var sortedList = list.Where(x => x.Key > DateTime.Now)
            .Select(x => x.Value);
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-05-09 13:53:11

看文件..。

来自有关Value属性的文档

IList<T>中值的顺序与SortedList<TKey, TValue>中的顺序相同。”

来自关于Keys属性的文档

IList<T>中键的顺序与SortedList<TKey, TValue>中的顺序相同。”

票数 2
EN

Stack Overflow用户

发布于 2017-05-09 13:58:13

您可以在这里查看源代码:

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,de670561692e4a20

显然,Keys属性只是这个类实例的包装器:

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,374aa21b960ae2e2

如果您查看GetEnumerator()方法,可以看到它创建了一个SortedListKeyEnumerator。这是它的源代码:

https://referencesource.microsoft.com/#System/compmod/system/collections/generic/sortedlist.cs,a4492235f85c77d8

据我所知,它的MoveNext()只是遍历包含的SortedList的键。

您可以以同样的方式了解Values的工作方式。

票数 0
EN

Stack Overflow用户

发布于 2017-05-09 14:00:17

如果您查看Enumerable.cs的源代码,您将看到没有谓词的重载只是尝试将源代码作为一个IList来处理,如果不起作用,它将使用枚举器返回第一个元素。索引和枚举数都应该由SortedList类在内部处理,以便得到适当的(排序)结果:

代码语言:javascript
复制
public static TSource First<TSource>(this IEnumerable<TSource> source) {
            if (source == null) throw Error.ArgumentNull("source");
            IList<TSource> list = source as IList<TSource>;
            if (list != null) {
                if (list.Count > 0) return list[0];
            }
            else {
                using (IEnumerator<TSource> e = source.GetEnumerator()) {
                    if (e.MoveNext()) return e.Current;
                }
            }
            throw Error.NoElements();
        }

带有谓词的重载工作方式略有不同,因为它使用枚举数对每个项执行谓词,查找第一个匹配项:

代码语言:javascript
复制
    public static TSource First<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate) {
        if (source == null) throw Error.ArgumentNull("source");
        if (predicate == null) throw Error.ArgumentNull("predicate");
        foreach (TSource element in source) {
            if (predicate(element)) return element;
        }
        throw Error.NoMatch();
    }

无论哪种方式,您都应该得到相同的(排序)结果。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43871635

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档