4

I have an int[] building; that I want to instantiate dynamically based on another array int[] info;

The info will hold int ranging from 0-48

To build the building array.. If there is a non-zero value in the info array at index ind I want to add that index to the building array.

So if info looks like this {0, 12, 24, 48} I'd like building to show {1, 2, 3} another example {12, 0, 0, 48} -> {0, 3}

Is there a neat one liner to accomplish this?

How I have been doing it

int[] info = new int[]{12, 0, 0, 48};
List<int> indxs = new List<int>();
for (int i = 0; i < info.Length; i++)
    if (info [i] > 0)
        indxs.Add(i);
int[] building = indxs.ToArray();
5
  • 2
    The language you're using is not C++, but the question is tagged C++. Please fix this inconsistency. Adjust either the tag or the example. Commented May 15, 2014 at 13:15
  • You might write a helper, say IndexesWhere, similar to System.Linq.Enumerable.Where. Commented May 15, 2014 at 13:19
  • 1
    Is there a particular reason you want it to be a one liner? You can create a method in a utility library, or better yet an extension method. You should always value readability over length. Commented May 15, 2014 at 13:23
  • @mason Not specifically, when performance isn't too much of an issue I like to make my code look nice. // I like the idea of extension methods. I can just push all the "mess" to one class and make the rest of my code look nice. Commented May 15, 2014 at 13:25
  • One liners do not necessarily make code look nice. Sure, in some cases you can do some very readable one liners with Linq or lambdas. But trying to make it a one liner for the sake of saving space is a bad idea. Commented May 15, 2014 at 13:27

2 Answers 2

4
var building = info.Select((i, idx) => i == 0 ? -1 : idx)
                   .Where(i => i != -1)
                   .ToArray();

This will get you the same array as you're getting now.

Here is the entire console application I used to prove it:

class Program
{
    static void Main(string[] args)
    {
        int[] info = new int[] { 12, 0, 0, 48 };
        List<int> indxs = new List<int>();
        for (int i = 0; i < info.Length; i++)
            if (info[i] > 0)
                indxs.Add(i);
        int[] building = indxs.ToArray();

        var newBuilding = info.Select((i, idx) => i == 0 ? -1 : idx)
            .Where(i => i != -1)
            .ToArray();
    }
}

Both building and newBuilding provide you with the same output.

Sign up to request clarification or add additional context in comments.

Comments

2
var filtered = info.Select((x,i) => new { Value = x, Index = i})
                   .Where(x => x.Value > 0)
                   .ToArray();

Comments

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.