1

I have an array of Vector3's from the polygon collider. I want to have an array of the indexes of all the Vector3's that are higher then a certain y.

    private void Awake()
    {
        polygonCollider2D = GetComponent<PolygonCollider2D>();
        float lowestY = polygonCollider2D.points.Min(x => x.y);
// So in the sentence below I want  to have a array of indexes instead of a array of vector3's.
        topPoints = polygonCollider2D.points.Where(x => x.y > lowestY).ToArray();
    }

Can I do this with Linq?

1
  • 1
    Take a look at the overload for Select that includes the index. Commented Mar 14, 2018 at 15:12

4 Answers 4

1

Yes you can use an overload of Select that includes the index like so

var topPointIndexes = polygonCollider2D.points
    .Select((p,i) => new{Point=p, Index=i})
    .Where(x => x.Point.y > lowestY)
    .Select(x => x.Index)
    .ToArray();

Another option is to just create the set of indexes up front

var points = polygonCollider2D.points;
var topPointIndexes = Enumerable.Range(0, points.Count())
    .Where(i => points[i].y > lowestY)
    .ToArray();
Sign up to request clarification or add additional context in comments.

Comments

0

The Select allows you to capture the index.

You can first select indexes and filter with the -1 'filter sentinel' value I used below,

topPointsIndexes = polygonCollider2D.points
    .Select((x, index) => (x.y > lowestY) ? index : -1) 
    .Where(i => i >= 0)
    .ToArray();

(or first expand the point and index together, and then filter, as juharr did in his answer)

Comments

0
indexesOfTopPoints = polygonCollider2D.points.Select((x, index) => index)
.Where(x => polygonCollider2D.points[x].y > lowestY).ToArray();

Comments

0

Try it

topPoints = polygonCollider2D.points.Select((x, i) => new {obj = x, i = i}).Where(x => x.y > lowestY).Select(x => x.i).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.