如何处理List>使用array[]操作符的项

本文关键字:List 操作符 array 使用 处理 何处理 | 更新日期: 2023-09-27 18:01:32

我的问题是:我有一个对象"Strip",我需要有这些条带的列表或数组"stripList"之后,我需要有一个列表从不同的stripList,我称之为"listOfStripList"。我知道我可以这样保存:

List<List<Strip>> listOfStripList=new List<List<Strip>>();

我想以这种方式拥有这些对象的原因是因为每次我都想访问每个stripList而不使用For循环。例如,我想说listOfStripList[1],这与条带的第一个列表有关。

是否有任何方法来定义这些列表数组?

如何处理List<List<>>使用array[]操作符的项

listOfStripList[0]会给你一个List<Strip>对象。调用listOfStripList[0][0]会得到listOfStripList第一个列表中的第一个项目

这里有一把小提琴:https://dotnetfiddle.net/XdDggB

using System;
using System.Collections.Generic;
public class Program
{
    public static void Main()
    {
        List<List<Strip>> listOfStripLists = new List<List<Strip>>();
        for(int j = 65; j < 100; j++){
            List<Strip> stripList = new List<Strip>();
            for(int i = 0; i < 10; i++){
                stripList.Add(new Strip(){myval = ((char)j).ToString() + i.ToString()});
            }
            listOfStripLists.Add(stripList);
        }// end list of list
        Console.WriteLine(listOfStripLists[0][1].myval);
    }

    public class Strip
    {
        public string myval {get;set;}  
    }
}

List<T>T[]都允许使用索引器(即[]操作符)。所以你可以像这样使用你的列表:

List<Strip> firstList = listOfStripList[0];

但是,如果您必须将其作为数组,则可以这样做:

List<Strip>[] arrayOfListStrip = listOfStripList.ToArray();
相关文章: