假设我有一个像这样的字符串数组:
string [] foos = { "abc","def","ghi" };
我想要一个包含每个字符串及其反向的新集合.所以结果应该是:
"abc","cba","fed","ghi","ihg"
我可以遍历数组,但这非常笨拙:
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)); }
有没有办法在LINQ中执行此操作?就像是
var results = from foo in foos select foo /* and also */ select Reverse(foo)
解决方法
var result = from foo in foos from x in new string[] { foo,Reverse(foo) } select x;
要么
var result = foos.SelectMany(foo => new string[] { foo,Reverse(foo) });
这将foos中的每个foo映射到一个由两个元素组成的数组:foo和Reverse(foo).然后它将所有这些双元素数组连接成一个大的可枚举数组.
{ { { "abc",{ "abc","abc",},=> { => "def",} "ghi",{ "ghi","ihg",} } } }
如果输出的顺序不那么重要,您还可以使用Reverse方法将原始数组与映射原始数组中每个元素的结果连接起来:
var result = foos.Concat(from foo in foos select Reverse(foo));
要么
var result = foos.Concat(foos.Select(Reverse));
{ { { "abc",=> "def",} } concat { "cba",} }