Can I select multiple items in LINQ?

Say I have a string array, for example:

 string [] foos = { "abc", "def", "ghi" }; 

I want a new collection containing each row and its reverse. Thus, the result should be:

  "abc", "cba", "def", "fed", "ghi", "ihg" 

I could just iterate over the array, but this is pretty awkward:

 string Reverse (string str) { return new string (str.Reverse ().ToArray ()); } List<string> results = new List<string> (); foreach (string foo in foos) { results.Add (foo); results.Add (Reverse(str)); } 

Is there any way to do this in LINQ? Something like

 var results = from foo in foos select foo /* and also */ select Reverse(foo) 
+6
c # linq
source share
2 answers
 var result = from foo in foos from x in new string[] { foo, Reverse(foo) } select x; 

or

 var result = foos.SelectMany(foo => new string[] { foo, Reverse(foo) }); 

This maps each foo to a foos array, which consists of two elements: foo and Reverse(foo) . Then it combines all these two-element arrays into one big enumerated one.

  {{{
 "abc", {
                                 "abc", "abc",
                                 "cba", "cba",
                                 },
 "def", => {=>
                                 "def", "def",
                                 "fed", "fed",
                                 }
 "ghi", {
                                 "ghi", "ghi",
                                 "ihg", "ihg",
                                 }
 }}}

If the order of your output is not so important, you can also combine the source array with the result of matching each element in the source array using the callback method:

 var result = foos.Concat(from foo in foos select Reverse(foo)); 

or

 var result = foos.Concat(foos.Select(Reverse)); 
  {{{
 "abc", "abc", "abc",
 "def", => "def", => "def",
 "ghi", "ghi", "ghi",
 }}
                                 concat
                                 {
                                 "cba", "cba",
                                 "fed", "fed",
                                 "ihg", "ihg",
                                 }}

+13
source share

I think your following is the following:

  static void Main(string[] args) { string[] foos = { "abc", "def", "ghi" }; string[] result = foos.Union(foos.Select(A=> new string(A.ToCharArray().Reverse().ToArray()))).ToArray(); foreach(string a in result) Debug.WriteLine(a); } 

"Tricks":

  • Use concatenation to result in a single sequence.
  • Convert the string to Char [] and undo this sequence
  • Use the string constructor that takes Char [] to create a new line for the sequence
0
source share

All Articles