0
Given a list of strings:
"A"
"B"
"C"
"D"

I will expect to get a list of lists of 2 items each one but with the second item repeated:

"A", "B"

"B", "C"

"C", "D"

What I am trying is the next any possible better solution?

        //result = List<string> {"A","B","C","D"}

        List<List<string>> obList = new List<List<string>>();
        List<string> tst = new List<string>(2);
        foreach (var s in result)
        {
            tst.Add(s);
            if (tst.Count == 2)
            {
                obList.Add(tst);
                tst = new List<string> { s };
            }
        }
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
Marcos Varela
  • 85
  • 1
  • 10
  • In case you don't want to use the overly complicated and generalized accepted answer from the linked duplicate -- which doesn't actually seem to address your question, which is about duplicating the second item -- you could try this: `var obList = result.Zip(result.Skip(1)).Select(p => new List { p.First, p.Second }).ToList();` – Jeff Jul 01 '20 at 18:34

1 Answers1

0

One solution would be to iterate the result List using a for loop and use the iterator to get the range of current element plus the next element in the list as a new list

//You would stop the loop at the second to last element in the result list
//That way you don't get a new list with only the last element and in this 
//code block, an index out of range exception the last element would cause 
//the exception as GetRange(i, 2) on the last element would be out of range
for(int i = 0; i < result.Count - 1; i++)
{
   //Grab the range    
   obList.Add(result.GetRange(i, 2).ToList());
}
Ryan Wilson
  • 10,223
  • 2
  • 21
  • 40
  • Hi! thanks for your answer! But with this solution in the first list i will only have 1 item – Marcos Varela Jul 01 '20 at 18:31
  • @MarcosVarela I screwed up on the `GetRange(int32, int32)` method. I needed to put the second parameter as the number of items to return, the first being the starting index. I updated the answer. Try it now. – Ryan Wilson Jul 01 '20 at 18:32