如何在C#的文本框中混合单词的顺序?

时间:2014-06-11 07:34:20

标签: c# textbox

当我按下按钮但是必须准确指定顺序时,我需要制作一个混合文本框中单词顺序的程序。用户将句子放在文本框中,因此每次句子都不同。订单必须由偶数和奇数混合。让我们说句子是“今天是美好的一天”。现在我们有5个单词,它们必须用奇数和偶数混合,所以顺序就像这个“今天美丽的日子”,因为偶数和奇数一起出现。今天[0],a [2]和day [4]这些单词有偶数,它们从最大到最小相互混合,所以它从4变为0.与奇数相同但偶数具有优先权(他们必须是第一个:4,2,0,3,1)。谁能举个例子说明我怎么做?

1 个答案:

答案 0 :(得分:4)

您可以使用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"