简体   繁体   English

Visual C#将自定义IEnumerable转换为字符串[]

[英]Visual C# converting custom IEnumerable to string[]

I am writing a plugin code in C# and there is a custom IEnumerable that is in fact an array of strings. 我正在用C#编写插件代码,并且有一个自定义IEnumerable,它实际上是一个字符串数组。 However no string operations can be done on the array elements because they are not of the type <string> . 但是,不能对数组元素执行任何字符串操作,因为它们不是<string>类型的。 But I need them to be strings and I have to operate on them as strings. 但是我需要它们成为字符串,并且必须将它们作为字符串进行操作。

So I have added these 2 lines of code to turn the array into string: 因此,我添加了以下两行代码以将数组转换为字符串:

var arrayRawSourceText = EditorController.ActiveDocument.ActiveSegmentPair.Source.AllSubItems.ToArray();
string[] arraySourceText = new string[arrayRawSourceText.Length];
for (int i = 0; i < arrayRawSourceText.Length; i++) { arraySourceText[i] = arrayRawSourceText[i].ToString(); }

Only two lines, yet I wonder if there is a simpler way of converting the array to <string> . 只有两行,但我想知道是否存在将数组转换为<string>的更简单方法。 Like a lambda expression or any other way to make this simpler. 像lambda表达式或其他任何使之更简单的方法。

If AllSubItems implement IEnumerable I guess this code snippet should work : 如果AllSubItems实现IEnumerable,我猜这个代码片段应该可以工作:

var arraySourceText = EditorController.ActiveDocument
                                      .ActiveSegmentPair
                                      .Source
                                      .AllSubItems
                                      .Select(t => t.ToString())
                                      .ToArray();

I have seen you already accepted an answer, But for further searchers maybe this will fit too: 我已经看到您已经接受了答案,但是对于其他搜索者来说,这也可能适合:

var arraySourceText = EditorController.ActiveDocument
                                  .ActiveSegmentPair
                                  .Source
                                  .AllSubItems
                                  .Cast<string>()
                                  .ToArray();

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

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