Search code examples
c#listindexingnotation

I want my values in a c# list to display this way


I want my values of my list to permanently display the way described with the Console.WriteLine(); (with index notation) , so I can write them to a text file that way. How to I go about "sorting" the list in this way. Any answers will be much appreciated. Thanks in advance. guys . Here is my code:

            List<string> list = new List<string>();
            list.AddRange(words);
            list.AddRange(words1);


            //Displays what word follows each element in the list
            Console.WriteLine("{0},{1}",list[0],list[1]);
            Console.WriteLine("{0},{1}",list[1], list[2]);
            Console.WriteLine("{0},{1}",list[2], list[3]);
            Console.WriteLine("{0},{1}",list[3], list[4]);
            Console.WriteLine("{0},{1}",list[4], list[5]);



            //list.ForEach(Console.WriteLine);






            File.WriteAllLines(@"C:\Users\David\Text.txt", list);//writes list to .txt file

Solution

  • This will create a new List<string> meeting your requirement from the original list:

    var newList = list.Take(list.Count-1)
                      .Select((x,i)=> string.Format("{0},{1}",x[i],x[i+1]))
                      .ToList();
    

    You can also try a normal for loop like this, it will modify the existing list directly:

    for(int i = 0; i < list.Count - 1; i++)
       list[i] = string.Format("{0},{1}", list[i], list[i+1]);