简体   繁体   中英

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. However no string operations can be done on the array elements because they are not of the type <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> . Like a lambda expression or any other way to make this simpler.

If AllSubItems implement IEnumerable I guess this code snippet should work :

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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