Konrad
Konrad

Reputation: 24651

Getting an object variable from List in C#

I have class with variables:

public class Items {
    public string name;
    public string ID;
}

and I have second class when I have List of object of first class

public class MyClass {
    public Items cheese;
    public List <Items> listOfItems = new List ();
    listOfItems.Add (cheese); // I know it should be in method or something but it's just an example
}

and I want get the name of the cheese, but using my list, because I have above 20 items in my list. In Java I can do it like:

listOfItems.get(1).name; // 1 is an index

How can I do it in C#? // Please don't try to improve my

Upvotes: 0

Views: 1529

Answers (2)

Nacho
Nacho

Reputation: 1013

The simple way:

listOfItems[1].name;

If you want a specific item try this:

var name = listOfItems.Find(x => x.ID == "1").name;

"1" is the example "Id" that you search.

Sorry for my english

I hope help you.

Upvotes: 2

psoshmo
psoshmo

Reputation: 1550

listOfItems[0].name;

Just remember to start counting at 0 ;)

Other than that its works the same way as java, just slightly different syntax

Upvotes: 3

Related Questions