如何访问列表中的特定列表?

时间:2012-12-03 10:53:17

标签: c# list sublist

我有一个List<List<string>>信息;这是其他3个列表。我需要能够在每个子列表上做三件事。我如何访问每个子列表?

为了更清晰,列表已添加到主列表中,如此

infomration.Add(sublist1);//where each sublist is a List<string> and information is a <List<List<string>>
infomration.Add(sublist2);
infomration.Add(sublist3);
reutrn information;

5 个答案:

答案 0 :(得分:3)

您希望对列表中的3个元素(列表)执行3个单独的操作。由于Lists被编入索引,为什么不以这种方式访问​​它们呢?

PerformOperationOne(myListofLists[0]);
PerformOperationTwo(myListofLists[1]);
PerformOperationThree(myListofLists[2]);

答案 1 :(得分:1)

您可以使用Enumerable.ElementAt(或列表的简单索引器):

List<string> first = lists.ElementAt(0);
List<string> second = lists.ElementAt(1);
List<string> third = lists.ElementAt(2);

doSomethingWith(first);
doSomethingWith(second);
doSomethingWith(third);

答案 2 :(得分:0)

    List<List<string>> lists = new List<List<string>>();
    lists.ForEach(i =>
    {
        i.Count();//do something
    });

答案 3 :(得分:0)

如果您需要单独访问每个列表,您可能应该使用Dictionary<string,List<string>>,但由于您需要对每个列表执行不同的操作,因此最好将三个单独的列表放在一起,而不是将它们全部放入单一组合结构。

这将允许您通过密钥访问每个列表。

var aList = myDictionary["the wanted list key"];

但是,如果您知道内部列表的索引,则可以通过索引访问它们:

var anInnerList = listOfLists[0];

答案 4 :(得分:0)

对集合中的所有列表执行相同的操作

foreach(List<string> list in information) {
    DoSomething(list);
}

但是,如果您需要对每个项目执行不同的操作,则可以根据以前的解决方案指定索引 - 或者,对于额外的功能,您可以将其放在交换机中以对每个实体执行多个不同的操作。

int counter = 0;
foreach(List<string> list in information) {
    switch(counter) {
        case 0:
            // First action
            list = DoSomething(list);
            break;
        case 1:
            // Second action
            list = DoSomethingElse(list);
            break;
        case 2:
            // Third action
            list = DoSomethingWeird(list);
            list = DoAnotherThing(list);
            break;
        default:
            // Do something if there's more than 3 items in the list
            SendErrorReport();
            break;
    }
    counter++;
}