简体   繁体   English

获取IList中的项目值?

[英]Getting values of items in IList?

Is there any way to get the values of items in the IList? 有没有办法获取IList中的项的值? It goes like this: 它是这样的:

Assume we have an IList list and a method private IList getValues(int ID) 假设我们有一个IList list和一个方法private IList getValues(int ID)

then we initialize IList list like: 然后我们初始化IList list如:

IList list = getValues(SelectedID)

After the processing, IList list now contains 2 elements, each with it's own collection: 在处理之后, IList list现在包含2个元素,每个元素都有自己的集合:

[0]
 {
   GroupName = "test01"
   GroupID = 1
 }

[1]
 {
   GroupName = "test02"
   GroupID = 2
 }

How will I get the GroupName of the first element? 我如何获得第一个元素的GroupName? I can't just call it like list[0].GroupName , can I? 我不能把它称为list[0].GroupName ,我可以吗?

If you know the type of the object, you can use this to get what you want. 如果您知道对象的类型,则可以使用它来获得所需的内容。

list.Cast<Group>().ElementAt(0).GroupName

Group as in your object name. 在对象名称中分组。

Try the following, you need to create a list with your custom object. 请尝试以下操作,您需要使用自定义对象创建一个列表。 I created a dummy class here named CustomClass, and creating a list with the known type. 我在这里创建了一个名为CustomClass的虚拟类,并创建了一个已知类型的列表。

public class CustomClass
    {
        public string GroupName { get; set; }
        public int GroupID { get; set; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        List<CustomClass> list = new List<CustomClass>();
        foreach (var x in list) {
            Console.WriteLine(x.GroupName);
        }

    }

You can use FindIndex method, example 您可以使用FindIndex方法,例如

class MyClass2
{
    public string Name { get; set; }
    public int Age { get; set; }
    public int Type { get; set; }
}


    List<MyClass2> myLists = new List<MyClass2>();
    myLists.Add(new MyClass2() { Age = 1, Name = "Mast", Type = 560 });
    myLists.Add(new MyClass2() { Age = 2, Name = "Oli", Type = 778 });
    myLists.Add(new MyClass2() { Age = 3, Name = "AS", Type = 9458 });
    myLists.Add(new MyClass2() { Age = 4, Name = "ABC", Type = 100 });

    int result1 = myLists.FindIndex(T => T.Type == 9458); //2
    int result2 = myLists.FindIndex(T => T.Name == "Oli"); //1

please refer http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx 请参阅http://msdn.microsoft.com/en-us/library/x1xzf2ca.aspx

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

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