使用select和bool数组过滤字符串数组

时间:2014-11-14 15:55:23

标签: c# .net

我需要获取字符串数组的所有元素,其中另一个bool数组中的索引为true。 在c#中,我正在寻找Select,但我不知道如何在索引

上使用
String[] ContentArray = {"Id","Name","Username"};
bool[] SelectionArray = {false,true,false};

2 个答案:

答案 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();
    }
}