首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

为什么C#.NET SortedList <T1,T2>实际上没有ElementAt?

在C#中,SortedList<T1, T2>是一个泛型类,用于存储一组键值对,其中键是唯一的,并按升序排序。SortedList<T1, T2>没有ElementAt方法的原因是它没有实现IEnumerable<KeyValuePair<T1, T2>>接口。这个接口提供了ElementAt方法,允许我们通过索引访问集合中的元素。

然而,SortedList<T1, T2>实现了IDictionary<T1, T2>接口,该接口提供了一种不同的方式来访问集合中的元素。我们可以使用Keys属性来获取SortedList<T1, T2>中的所有键,然后使用索引访问相应的值。

例如,如果我们有一个SortedList<int, string>,我们可以使用以下代码来访问第一个元素:

代码语言:csharp
复制
var sortedList = new SortedList<int, string>();
sortedList.Add(1, "one");
sortedList.Add(2, "two");
sortedList.Add(3, "three");

int key = sortedList.Keys.ElementAt(0);
string value = sortedList[key];

在这个例子中,我们使用ElementAt方法从Keys属性返回的集合中获取第一个键,然后使用该键从SortedList<int, string>中获取相应的值。

如果您需要使用ElementAt方法访问SortedList<T1, T2>中的元素,可以将其转换为IEnumerable<KeyValuePair<T1, T2>>,如下所示:

代码语言:csharp
复制
var sortedList = new SortedList<int, string>();
sortedList.Add(1, "one");
sortedList.Add(2, "two");
sortedList.Add(3, "three");

var kvp = sortedList.Cast<KeyValuePair<int, string>>();
KeyValuePair<int, string> firstElement = kvp.ElementAt(0);

在这个例子中,我们使用Cast<KeyValuePair<int, string>>方法将SortedList<int, string>转换为IEnumerable<KeyValuePair<int, string>>,然后使用ElementAt方法获取第一个元素。

总之,SortedList<T1, T2>没有ElementAt方法是因为它没有实现IEnumerable<KeyValuePair<T1, T2>>接口。但是,您可以使用Keys属性或将SortedList<T1, T2>转换为IEnumerable<KeyValuePair<T1, T2>>来访问其元素。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券