简体   繁体   English

从C#中的List获取对象变量

[英]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. 我想获取奶酪的名称,但是要使用我的列表,因为我的列表中有20多个项目。 In Java I can do it like: 在Java中,我可以这样做:

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

How can I do it in C#? 如何在C#中做到这一点? // Please don't try to improve my //请不要尝试改善我的

listOfItems[0].name;

Just remember to start counting at 0 ;) 只记得从0开始计数;)

Other than that its works the same way as java, just slightly different syntax 除此之外,它的工作方式与Java相同,只是语法略有不同

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. “ 1”是您搜索的示例“ Id”。

Sorry for my english 对不起我的英语不好

I hope help you. 希望对您有帮助。

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

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