Reputation: 2802
I have a List of strings
List<string> myList = new List<string>();
myList.Add(string1_1);
myList.Add(string1_2);
myList.Add(string2_1);
myList.Add(string2_2);
myList.Add(string3_1);
myList.Add(string3_2);
Now, after some magic, I want to combine the elements of the List, making them like this
myList[0] = string1_1 + string1_2
myList[1] = string2_1 + string2_2
myList[2] = string3_1 + string3_2
thus also cutting the size of the List in half. How can this be achieved?
Upvotes: 0
Views: 1391
Reputation: 1022
You could try something like this:
var half = myList
.Select((s,idx) => s + (idx < myList.Count() - 1 ? myList[idx +1] : string.Empty) )
.Where((s,idx) => idx % 2 == 0)
.ToList();
You can do a projection of all items in the form string[i] + string[i+1] (being careful to check that the string[i+1] element exists):
.Select((s,idx) => s + (idx < myList.Count() - 1 ? myList[idx +1] : string.Empty) )
Then filter only the even elements:
.Where((s,idx) => idx % 2 == 0)
Upvotes: 1
Reputation: 11252
A simple for loop would work:
List<string> inputList = new List<string>();
List<string> outputList = new List<string>();
for (int i = 0; i < inputList.Count; i += 2) // assumes an even number of elements
{
if (i == inputList.Count - 1)
outputList.Add(inputList[i]); // add single value
// OR use the continue or break keyword to do nothing if you want to ignore the uneven value.
else
outputList.Add(inputList[i] + inputList[i+1]); // add two values as a concatenated string
}
For loops are good for looping and dealing with pairs or triplets of elements at a time.
Upvotes: 6
Reputation: 125660
I would definitely go with a for
loop approach provided by Trevor, but if you'd like to do it using LINQ you can use GroupBy
and string.Join
:
myList = myList.Select((x, i) => new { x, i })
.GroupBy(x => x.i / 2)
.Select(g => string.Join("", g.Select(x => x.x)))
.ToList();
Upvotes: 6