Building int [] from values ​​in another int []

I have int[] building;one that I want to dynamically create based on another arrayint[] info;

infowill contain inta range from 0 to 48

To build an array building.. If there is a nonzero value in the array infoin the index ind, I want to add this index to the array building.

So if infoit looks like this: {0, 12, 24, 48}I would like to build to show {1, 2, 3}another example {12, 0, 0, 48}{0, 3}

Is there a neat one liner to accomplish this?

How i did 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();
+4
source share
2 answers
var building = info.Select((i, idx) => i == 0 ? -1 : idx)
                   .Where(i => i != -1)
                   .ToArray();

This will give you the same array as now.

, :

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

building newBuilding .

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

Source: https://habr.com/ru/post/1540704/


All Articles