如何从C#中的列表中获取索引值?

时间:2015-05-27 12:39:01

标签: c#

enter image description here

我有以下代码,我得到索引和值例如 index[0] value[0]"example"[1]"example" [2]"example"我想一次只访问一个索引的所有值

foreach (var pair in profession.Professions.Select((x, i) => new { Index = i, Value = x }))
{
    Console.WriteLine(pair.Index + ": " + pair.Value);
}

例如:当用户选择列表框中的第一项并且该项索引为[0]且值为[0]1 [1]480[2]749[3]270时,我想在messagebox中显示所有值。

1 个答案:

答案 0 :(得分:0)

由于您的代码只是部分且不太清楚,我会根据您提供的图片给出一个镜头:

//Defining the structure like in your example
static List<int[]> rootArray = new List<int[]>{
        new int[]{1,5,7,10},
        new int[]{2,4,6,8},
        new int[]{3,6,9,12}
    };

static void Main(string[] args)
    {
        //Same loop you posted in your OP, only added a .Where after the initial .Select just to get elements with Index == 0
        foreach(var p in rootArray.Select((x,i) => new {Index = i, Value = x}).Where(f => f.Index == 0).Select(x => x.Value))
        {
            //Since this is a List<int[]> your values are int arrays hence you need a loop to display all the values in it.
            foreach(var i in p)
            {
                Console.WriteLine(i);
            }
        }

        Console.ReadLine();
    }

希望这有帮助。