1

I need to get all element of a string array where the index in another array of bool is true. In c#, i was looking Select but i don't know how to use on index

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

2 Answers 2

4

I think you're looking for:

IEnumerable<string> strings =
    ContentArray.Where((str, index) => SelectionArray[index]);

Which for your example will yield an IEnumerable<string> containing "Name".

However, if your SelectionArray is shorter than your ContentArray, you will get an index out of bounds exception.

If that's possible, you could simply add a length check, assuming you want an index greater than the length of SelectionArray to return false:

IEnumerable<string> strings =
    ContentArray.Where(
        (str, index) => index < SelectionArray.Length && SelectionArray[index]);
Sign up to request clarification or add additional context in comments.

1 Comment

There's an override of Where that gives you the index.
1

You could also use IEnumerable.Zip(). Here's a sample:

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

2 Comments

+1 for Zip, although you could use an anonymous type instead of a tuple
Yeah - but I think the sample illustrates the point. So many ways to skin this cat... :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.