我需要获取字符串数组的所有元素,其中另一个bool数组中的索引为true。 在c#中,我正在寻找Select,但我不知道如何在索引
上使用String[] ContentArray = {"Id","Name","Username"};
bool[] SelectionArray = {false,true,false};
答案 0 :(得分:4)
我认为你在寻找:
IEnumerable<string> strings =
ContentArray.Where((str, index) => SelectionArray[index]);
对于您的示例,这将产生包含IEnumerable<string>
的{{1}}。
但是,如果您的"Name"
比SelectionArray
短,您将获得索引超出范围的例外情况。
如果可能的话,你可以简单地添加一个长度检查,假设你想要一个大于ContentArray
长度的索引来返回SelectionArray
:
false
答案 1 :(得分:1)
您也可以使用IEnumerable.Zip()
。这是一个示例:
class Program
{
static void Main(string[] args)
{
String[] ContentArray = { "Id", "Name", "Username" };
bool[] SelectionArray = { false, true, false };
var selected = ContentArray.Zip(SelectionArray, (s, b) =>
new Tuple<string, bool>(s, b))
.Where(tuple => tuple.Item2)
.Select(tuple => tuple.Item1)
.ToList();
foreach (var s in selected)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}