【问题标题】:How do you store a list of objects in an array?如何将对象列表存储在数组中?
【发布时间】:2021-08-27 22:39:15
【问题描述】:

我正在寻找一种将对象列表存储在数组中的方法。

例如

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

然后能够从数组中的对象获取信息,比如:

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

我一直在网上寻找并找到了一种涉及列表的方法,但我不明白如何使用它或它是如何工作的。

【问题讨论】:

  • 好吧,MyObject[] array = new[] {obj1, obj2, obj3};

标签: c# arrays object


【解决方案1】:

看看IList接口:https://docs.microsoft.com/en-us/dotnet/api/system.collections.ilist?view=net-5.0

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

}

您可以通过array.ElementAt(0).x访问元素

【讨论】:

  • 哇!非常感谢。这太快了。我会把它标记为答案,但你回答得太快了,我还不能。 :)
  • 它应该是 List array = new List(),假设 myObject.x 是有效的。
  • 你提到了IList 然后不要在你的代码中使用它。由于引入了IReadOnlyList,因此通常应优先避免使用IList
  • array.ElementAt(0).x 也不是一个好建议。 array[0].x 更简单、更快捷。虽然名称的选择不是最佳的(因为数组实际上不是数组)。
【解决方案2】:

你有不同的可能性来完成这个:

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()}";
}

dotnet fiddle 上的工作示例

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 1970-01-01
    • 2020-09-30
    • 2014-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多