简体   繁体   中英

How do you store a list of objects in an array?

I'm looking for a way to store a list of objects within an array.

ex.

int[] array = {obj1, obj2, obj3};

And then be able to access information from the objects in the array, like:

Console.WriteLine(array[0].x);

I have been looking online and found a way to do it involving a list, but I didn't understand how to use it or how it worked.

Have a look at the IList interface: https://docs.microsoft.com/en-us/dotnet/api/system.collections.ilist?view=net-5.0

IList<int> array = new List<int>()
{
    obj1, obj2, obj3

}

You can access the elements by array.ElementAt(0).x

You have different possibilities to accomplish this:

public static void Main()
{
    ClassA[] array = { new ClassA(), new ClassA(), new ClassA()};
    
    for(var i = 0; i< array.Length; i++)
    {
        // https://docs.microsoft.com/de-de/dotnet/csharp/programming-guide/arrays/
        Console.WriteLine(array[i].Value);
    }
    Console.WriteLine("");
        
    foreach(var item in array)
    {
        // https://docs.microsoft.com/de-de/dotnet/csharp/programming-guide/arrays/using-foreach-with-arrays
        Console.WriteLine(item.Value);
    }
    Console.WriteLine("");
    
    var enumerable = array.AsEnumerable();
    for(var i = 0; i< array.Length; i++)
    {
        // https://docs.microsoft.com/de-de/dotnet/api/system.linq.enumerable.elementat?view=net-5.0
        Console.WriteLine(enumerable.ElementAtOrDefault(i)?.Value);
    }
    Console.WriteLine("");
    
    // All these things also apply for the int[] array like in your question
    int[] array2 = { 1, 2, 3};
    for(var i = 0; i< array.Length; i++)
    {
        Console.WriteLine(array2[i]);
    }

    // Or use a List<T> instead
    var list = new List<ClassA>();
    list.Add(new ClassA());
    list.Add(new ClassA());
    list.Add(new ClassA());
    
    for(var i = 0; i< array.Length; i++)
    {
        Console.WriteLine(enumerable.ElementAtOrDefault(i)?.Value);
    }
}

class ClassA
{
    public string Value { get; set; } = $"{Guid.NewGuid()}";
}

Working example on dotnet fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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