简体   繁体   English

如何将string.Join应用于文本框数组?

[英]How to apply string.Join to Textbox array?

In my C# WinForm application, I have an array of TextBox on my form, which looks like: 在我的C#WinForm应用程序中,我的窗体上有一个TextBox数组,如下所示:

[MyTextBox[0]] . [MyTextBox [0]]。 [MyTextBox[1]] . [MyTextBox [1]]。 [MyTextBox[2]] . [MyTextBox [2]]。 [MyTextBox[3]] . [MyTextBox [3]]。 [MyTextBox[4]] [MyTextBox [4]]

As you can see, there is a separator "." 如您所见,有一个分隔符“。” between each of them. 他们之间。 The user will enter 5 different values in those TextBoxes , and submit them. 用户将在那些TextBoxes输入5个不同的值,然后提交它们。 When processing, I would like to gather all these 5 TextBoxes as one string separated by ".". 处理时,我希望将所有这5个TextBoxes收集为一个字符串,并用“。”分隔。 For example, if the user entered 例如,如果用户输入

[34] . [34]。 [56] . [56]。 [78] . [78]。 [90] . [90]。 [12] [12]

and submitted, I would like to process this as one string: 34.56.78.90.12 . 并提交,我想将其作为一个字符串处理: 34.56.78.90.12 I was thinking using string.Join(".", strArray) would be nice and elegant, but I realized that this is an array of TextBox , not an array of string. 我当时在想使用string.Join(".", strArray)会很好,但是我意识到这是TextBox的数组,而不是string的数组。 To extract the text portion from the TextBox , I have to use MyTextBox[index].Text but this obviously won't work with string.Join(".", strArray) . 要从TextBox提取文本部分,我必须使用MyTextBox[index].Text但这显然不适用于string.Join(".", strArray)

Now, I ended up writing the following code: 现在,我最终编写了以下代码:

string[] dataEntered = new string[5];
for(int i=0; dataEntered.Length; i++)
{
    dataEntered[i] = MyTextBox[i].Text;
}
string str = string.Join(".", dataEntered);

or, using a string concatenation within a loop too, adding "." 或者,也可以在循环中使用字符串连接,添加“。” each time except after the last value. 每次,除了最后一个值之后。

But these are both kind of ugly, and I was wondering if there is any better way of achieving this. 但是这些都很难看,我想知道是否有更好的方法可以实现这一目标。 Can someone give me advice, please? 有人可以给我建议吗?

So MyTextBox is the TextBox[] ? 那么MyTextBoxTextBox[]吗? You can use LINQ: 您可以使用LINQ:

IEnumerable<string> alltexts = MyTextBox.Select(txt => txt.Text);
string str = string.Join(".", alltexts);

使用linq:

string str = string.Join(".", MyTextBox.Select(t => t.Text));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM