質問

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();
役に立ちましたか?

解決

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.

他のヒント

var filtered = info.Select((x,i) => new { Value = x, Index = i})
                   .Where(x => x.Value > 0)
                   .ToArray();
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top