简体   繁体   English

通过索引获取列表项

[英]Getting a list item by index

I've recently started using c# moving over from Java.我最近开始使用从 Java 转移过来的 c#。 I can't seem to find how to get a list item by index.我似乎无法找到如何通过索引获取列表项。 In java to get the first item of the list it would be:在java中获取列表的第一项将是:

list1.get(0);

What is the equivalent in c#? c# 中的等价物是什么?

list1[0];

假设列表的类型定义了一个索引器。

You can use the ElementAt extension method on the list.您可以使用列表中的 ElementAt 扩展方法。

For example:例如:

// Get the first item from the list

using System.Linq;

var myList = new List<string>{ "Yes", "No", "Maybe"};
var firstItem = myList.ElementAt(0);

// Do something with firstItem

Visual Basic, C#, and C++ all have syntax for accessing the Item property without using its name. Visual Basic、C# 和 C++ 都具有无需使用其名称即可访问 Item 属性的语法。 Instead, the variable containing the List is used as if it were an array.相反,使用包含 List 的变量就好像它是一个数组一样。

List[index]

See for instance: https://msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx参见例如: https : //msdn.microsoft.com/en-us/library/0ebtbkkc(v=vs.110).aspx

Old question, but I see that this thread was fairly recently active, so I'll go ahead and throw in my two cents:老问题,但我看到这个线程最近很活跃,所以我会继续投入我的两分钱:

Pretty much exactly what Mitch said.米奇说的差不多。 Assuming proper indexing, you can just go ahead and use square bracket notation as if you were accessing an array.假设索引正确,您可以继续使用方括号表示法,就像访问数组一样。 In addition to using the numeric index, though, if your members have specific names, you can often do kind of a simultaneous search/access by typing something like:但是,除了使用数字索引之外,如果您的成员具有特定名称,您通常可以通过键入以下内容来同时进行搜索/访问:

var temp = list1["DesiredMember"];

The more you know, right?你知道的越多,对吧?

.NET List data structure is an Array in a "mutable shell". .NET List数据结构是“可变外壳”中的Array

So you can use indexes for accessing to it's elements like:因此,您可以使用索引来访问它的元素,例如:

var firstElement = myList[0];
var secondElement = myList[1];

Starting with C# 8.0 you can use Index and Range classes for accessing elements.C# 8.0开始,您可以使用IndexRange类来访问元素。 They provides accessing from the end of sequence or just access a specific part of sequence:它们提供从序列末尾访问或​​仅访问序列的特定部分:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges together:您可以将索引和范围组合在一起:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.您也可以使用 LINQ ElementAt方法,但对于 99% 的情况,这确实没有必要,只是性能缓慢的解决方案。

you can use index to access list elements您可以使用索引来访问列表元素

List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM