Michael
Michael

Reputation: 13616

How to retrieve the specific indexes from array?

I have this array :

 Point[] arr  = samples.pointsArray;

I using this row to retrieve all elements that satisfy condition:

var maxXCol = arr.Where( p => maxX.X == p.X );

Any idea how to modify row above, to get only the indexes of these elements?

Thank you in advance!

Upvotes: 0

Views: 100

Answers (6)

Chris Pfohl
Chris Pfohl

Reputation: 19044

EDIT

Use the version of Select that takes both the index and the object and create an anonymous object with the object and index inside it. It would look like this:

someEnumerable.Select((obj, idx) => new {Item = obj, Index = idx})

You'll need to do this before you use Where so that the original index remains intact after the filter operation.

In the following operations you can use the item like so:

x => x.Item

and the index like so:

x => x.Index

Upvotes: 2

Alex Filipovici
Alex Filipovici

Reputation: 32541

var maxXCol = arr
    .Select((a, b) => new { b, a })
    .Where(p => maxX.X == p.a.X)
    .Select(i=>i.b);

Upvotes: 1

Kirill Bestemyanov
Kirill Bestemyanov

Reputation: 11964

Try this:

arr.Select((e,i)=>new{index=i, value=e}).Where(ei=>ei.value.X==maxX.X).Select(ei=>ei.index);

Upvotes: 1

Honza Brestan
Honza Brestan

Reputation: 10947

You can use Select overload which takes an index, and project that index together with the original row. Then take only the index for the result collection.

var maxXCol = arr
    .Select((p, index) => new { Item = p, Index = index })
    .Where(p => maxX.X == p.Item.X)
    .Select(x => x.Index);

Upvotes: 1

Habib
Habib

Reputation: 223187

You may select the value first with the index in anonymous type, later you filter it with your condition and then select the index.

var result = arr.Select((g, index) => new { g, index })
              .Where(r => maxX.X == r.X)
              .Select(t => t.index);

Upvotes: 1

L.B
L.B

Reputation: 116098

var maxXCol = arr.Select((p, inx) => new { p,inx})
                 .Where(y => maxX.X == y.p.X)
                 .Select(z => z.inx);

Upvotes: 1

Related Questions