gpt4 book ai didi

c# - 在 LINQ 中,我可以选择多个项目吗?

转载 作者:太空狗 更新时间:2023-10-29 21:03:14 28 4
gpt4 key购买 nike

假设我有一个像这样的 string 数组:

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

我想要一个包含每个字符串及其反转的新集合。所以结果应该是:

    "abc",
"cba",
"def",
"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 映射到一个由两个元素组成的数组:fooReverse(foo)。然后它将所有这些双元素数组连接成一个大型可枚举数组。

{                           {                             {"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 concatenate the original array with the result of mapping each element in the original array using the Reverse method:

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

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

关于c# - 在 LINQ 中,我可以选择多个项目吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3850590/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com