I have a list:
List<string> theList = new List<string>;
There are a few elements in the List. And now I want to get an item by the index. e.g. I want to get element number 4. How can I do it?
Just use the indexer
string item = theList[3];
Note that indexes in C# are 0 based. So if you want the 4th element in the list you need to use index 3. If you want the 5th element you would use index 4. It's unclear from your question which you intended
The indexer is a common feature on .Net collection types. For lists it's generally index based, for maps it's key based. The documentation for the type in question will tell you which and if it's available. The indexer member will be listed though as the property named Item
http://msdn.microsoft.com/en-us/library/0ebtbkkc.aspx
To get 4th item, you can use indexer:
string item = theList[3];
if you prefer to use methods, then you can use ElementAt or (ElementAtOrDefault):
string item = theList.ElementAt(3);
You can use the Indexer to get the Item at selected index
string item = theList[3];
Use the indexer:
string the4th = theList[3];
Note that this throws an exception if the list has only 3 items or less since the index is always zero-based. You might want to use Enumerable.ElementAtOrDefault then:
string the4th = theList.ElementAtOrDefault(3);
if(the4th != null)
{
// ...
}
ElementAtOrDefault returns the element at the specified index if index < list.Count and default(T) if index >= theList.Count. So for reference types(like String) it returns null and for value types their default value(e.g. 0 for int).
For collection types which implement IList<T>(arrays or lists) it uses the indexer to get the element, for other types it uses a foreach loop and a counter variable.
So you could also use the Count property to check if the list contains enough items for the index:
string the4th = null;
if(index < theList.Count)
{
the4th = theList[index];
}
use the Indexer Syntax:
var fourthItem = theList[3];
this should do it, access via array index.
theList[3]
its 3 as index's start at 0.
You can use the Indexer to get the Item at selected index
string item = theList[3];
Or if u want to get the id (if accessing from database) define a class e.g.
public class Person
{
public int PId;
public string PName;
}
and access as follow
List<Person> theList = new List<Person>();
Person p1 = new Person();
int id = theList[3].PId
Related
I've an IEnumerable list named list. It keeps these sample values:
I want to access and assign to any variables these Count, Start and End values, whenever I want. How can I do this?
The IEnumerable itself doesn't have Count, Start, or End. It's elements do, so you'll need to identify the element in the collection from which you want to read those values. For example, to read the values on the first element:
var firstCount = list.First().Count;
var firstStart = list.First().Start;
var firstEnd = list.First().End;
Or if you want to get a collection of all the Count values, something like this:
var allCounts = list.Select(c => c.Count);
You're operating on a collection of elements, not a single element. So to get information from any particular element you first need to identify it from the collection. And there are lots of methods you can chain together to identify any given element or set of elements.
Use a loop ?
foreach(var item in list)
{
var count = item.Count;
}
Or use ToList and convert it to List<T> then you can access your value with index:
var myList = list.ToList();
var count = myList[0].Count;
Also if you know the type you can cast your IEnumerable to IList<T> in order to use indexer.
It's possible to access the list with Linq using the namespace
using System.Linq;
like so
var firstListElement = list.ElementAt(0);
var firstListElementCount = firstListElement.Count;
// do more stuff with my first element of the list
Try:
list.Count()
list.First() or list.FirstOrDefault()
list.Last() or list.LastOrDefault()
I have two lists:
public static List<Dinosaur> Dinosaurs = new List<Dinosaur>();
public static List<DinosaurSpecies> DinosaurSpeciesList = new List<DinosaurSpecies>();
I want to use the Species in the first list to find the key of the Species in the second list. The following throws a 'has some invalid arguments' but it does illustrate what I'm trying to do:
int index = MainWindow.DinosaurSpeciesList.FindIndex(MainWindow.Dinosaurs[i].Specie);
In other words, where does the Species in the Dinosaurs list [index] appear in the list of all DinosaurSpecies?
You can do this by passing a predicate to the FindIndex method:
int index = MainWindow.DinosaurSpeciesList.FindIndex(x => x.Specie == MainWindow.Dinosaurs[i].Specie);
Basically, you are saying: Find the index of the element whos Specie property is equal to the specified Dinosaur.Specie property
A simplified and more understandable example might be:
Dinosaur dinosaur = GetDinosaurToFindSpeciesInformationFor();
int index = DinosaurSpeciesList.FindIndex(x => x.Specie == dinosaur.Specie);
Of course, if you then plan to only use the index to get the DinosaurSpecies object anyway, you could do this:
DinosaurSpecies species = DinosaurSpeciesList.SingleOrDefault(x => x.Specie == dinosaur.Specie);
//NOTE: species will be null if there are no matches, or more than one match
Your parameters to FindIndex are wrong. The single-parameter form requires a lambda (or more specifically, a Predicate<T>):
int index = MainWindow.DinosaurSpeciesList.FindIndex(x => x.Specie.Equals(MainWindow.Dinosaurs[i].Specie));
Depending on what your DinosaurSpecies class looks like, of course.
ps. I like dinosaurs
I have such code:
List<Vector3> list = fillTheList();
How can I get element from it on specyfied position?
You can get it by using its indexer.
var item = list[index];
Lists also have indexers like arrays do.
For example if you want to have the second item in the list you would write:
var vectorFromList = list[1]
List has an indexer that accepts integer, the index of the element in the List
ls[0] // gets the first element
ls[1] // gets the second element
i have a list contains set of strings, i want to fetch the data present in the list based on index, with out using iterator.. is there any functions like get() or getat() some sort of method using which we can fetch?
myList[index] is the way to go
List<string> myList = new List<string>();
myList.Add("string 1");
myList.Add("String 2");
Console.WriteLine(myList[0]); // string 1
Console.WriteLine(myList[1]); // String 2
List<string> myList = new List<string();
//add some elements to the list
//then get the third element
string thirdElement = myList[2];
You can just do:
item = list[i];
Use the overloaded index operator.
List<String> list; // ... initialize, populate list
String element = list[1]; // get the element at index 1
If your collection implements IList<T>, just use indexer. Otherwise, if your collection only allows forward-only access (that is, only implements IEnumerable<T>) you can use ElementAt() method, but it still uses iterator under the hood.
I don't know what kind of list you're talking about exactly, but most collections in .net have a CopyTo function, and you can access individual items with the [] operator.
List<string> list = new List<string>();
list.Add("lots of strings");
//If you want to print all the strings you can do:
foreach(string str in list)
Console.WriteLine(str);
//If you want to modify each string in the list, make each lower case for example,
// you can do. this is working by using the index of the elements in the list:
for(int i = 0; i < list.Count; i++)
list[i] = list[i].ToLower();
If you use the generic type List (or another implementation of IList) you can use the index operator to directly access items at certain positions: item = myList[3]
If you use a type that only implements IEnumerable you should use the ElementAt() function.
What's your reason to avoid the use of iterators?
All that i'm trying to do is to compare, for each value in a listbox, its value with a chosen one and then set the match index as selected.
For some reason the exception in the title is raised. I don't understand why though.
Code:
foreach(SurfaceListBoxItem n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
Thanks!
In WPF, List.Items does not necessarily contain collection of ListBoxItem, instead it only contains data values, and the Item Container of the data is derived, to set value, you must simply set current to selected item.
There is no need to iterate, you can simply do following,
BackgroundsList.SelectedItem = current;
The C# foreach statement does an implicit cast for you from the type of the element returned by Items to the specified SurfaceListBoxItem type. At runtime the returned string can not be casted to SurfaceListBoxItem. You can solve this by using var instead of SurfaceListBoxItem
foreach(var n in BackgroundsList.Items)
{
if (n.ToString() == current) BackgroundsList.SelectedItem = n;
}
Or, of course, you can use LINQ:
BackgroundsList.SelectedItem = (
from n in BackgroundList.Items
where n.ToString() == current
select n).FirstOrDefault();