• Status: Solved
• Priority: Medium
• Security: Public
• Views: 665

# Reverse Concat List

Experts,

I have a list, and I need to reverse it and then concat it to itself. This might be really silly question.

Example : Original List  1 2 3 4
Altered List  1 2 3 4 4 3 2 1

Reverse() method returns a Void. I was planning on DList.Concat(DList.Reverse());

Whats the fasted way to achieve this?
0
San24
• 4
• 3
• 2
2 Solutions

Commented:
Just thinking about it without testing:
List<int> list1 = new List<int>();
List<int> list2 = new List<int>();

// fill list1

list1.CopyTo(list2);
list2.Reverse();

0

Author Commented:
Is there any other way to do it?
0

Commented:
What is your ultimate goal? Are you looking for the fastest way to do this? If so, it would be useful to know what the underlying structure of the list is. Is it an Array, List<>, SortedList<>? What is it? I've never heard of a DList.
0

Author Commented:
Eric,

Yes, the fastest way to do it. DList is just a simple double list. List<double>

Lets say, I have a list 0 1 2 3 4 - The altered list will look like 0 1 2 3 4 4 3 2 1. So, I have to create a new list, copy, give it a range and then concat it.
0

Commented:
You could also do it this way, which might be a little more efficient. But I can't think of anything else with a List<double>.
List<double> mylist;
int len = mylist.Count;
List<double> newlist = List<double>(2 * len);
for (int i = 0, j = 2 * len - 1; i < len; i++, j--)
{
newlist[i] = newlist[j] = mylist[i];
}
0

Commented:
Oops, I forgot one detail. The items of the list were not allocated. I've changed it a bit.
List<double> mylist;
int len = mylist.Count;
List<double> newlist = List<double>(2 * len);
for (int i = 0, j = 2 * len - 1; i < len; i++, j--)
{
newlist[j] = mylist[i];
}
0

Commented:

Similar to the first but working one solution :)

Output:

1
2
3
4
4
3
2
1
private void button2_Click(object sender, EventArgs e)
{
List<int> lst1 = new List<int>(new int[] { 1, 2, 3, 4 });
List<int> lst2 = new List<int>(lst1);
lst2.Reverse();
foreach (int i in lst1)
{
System.Diagnostics.Debug.WriteLine(i.ToString());
}

}
0

Commented:
Also, my version with loops, might be more efficient than above my code...
private void button2_Click(object sender, EventArgs e)
{
List<int> lst1 = new List<int>(new int[] { 1, 2, 3, 4 });
List<int> lst2 = new List<int>();// straight + reversed list
for (int i = 0; i < lst1.Count * 2; i++)
{
if (i < lst1.Count)
else
indexToAdd = lst1.Count*2 - 1 - i;

}

// print out
foreach (int i in lst2)
{
System.Diagnostics.Debug.WriteLine(i.ToString());
}

}
0

Author Commented:
Eric and Jimbel...Thanks a lot. This is what I`m doing

List<double> TempX = new List<double>();
TempX.Reverse();
TempX.RemoveRange(XCnt - 1, 1);
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.