Reputation: 33
I need to make a program that mixes the order of words in a textbox when I press the button but the order must be exactly specified. The user puts the sentence in the textbox so the sentence is different every time. The order must be mixed by even and odd numbers. Lets say the sentence is "today is a beautiful day". Now we have 5 words and they must be mixed by odd numbers and even numbers so the order is like this "day a today beautiful is" because even numbers and odd numbers go together. today [0], a [2] and day [4] these words have even numbers and they mix with each other from the biggest to the smallest so it goes from 4 to 0. The same with odd numbers but even numbers have priority (they must be the first: 4,2,0,3,1). Can anybody give me an example of how I can do this?
Upvotes: 1
Views: 160
Reputation: 460068
You can use LINQ-power:
string text = "today is a beautiful day";
var mixedWords = text.Split() // split by white-spaces
.Select((word, index) => new { word, index }) // select anonymous type
.GroupBy(x => x.index % 2) // remainder groups to split even and odd indices
.OrderBy(xg => xg.Key) // order by even and odd, even first
.SelectMany(xg => xg // SelectMany flattens the groups
.OrderByDescending(x => x.index) // order by index descending
.Select(x => x.word)); // select words from the anonymous type
string newText = string.Join(" ", mixedWords); // "day a today beautiful is"
Upvotes: 4