Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does LINQ work on Index?

Tags:

arrays

c#

linq

Lets say i have an array

byte[] myarr = {1,4,3,4,1,2,1,2,4,3,1,4,2};    

myarr will be of length 13 (0-12 Index) which will also be the length of int[] val.

int[] val = new int[13];

I want to check index of myarr where its value is 4 i.e. 1,3,8,11.

Then i want

val[1]++;
val[3]++;
val[8]++;
val[11]++;

One way of doing this is using for loop

for(int i=0; i<myarr.length; i++)
{
   if(myarr[i] == 4)
      val[i]++;
}

We can use Array.indexof but it returns the first index of that value meaning that value has to be unique and my myarr has lots of same values.

Can this be done using linq?

like image 418
Nikhil Agrawal Avatar asked Apr 13 '12 09:04

Nikhil Agrawal


2 Answers

This is what I ended up doing in LINQ (update included):

myarr.Select((b, i) => b == 4 ? i : -1)
    .Where(i => i != -1)
    .ToList().ForEach(i => val[i]++);

Your non-LINQ version is obviously much more succinct and readable, so I think you should use that.

like image 138
Cristian Lupascu Avatar answered Nov 01 '22 02:11

Cristian Lupascu


You can, but it won't be simpler. LINQ will only help you with the query part, the update part has to be done in a foo loop, but since the array contains value types you need to get indexes from your LINQ-query and not the actual values and you have won nothing.

like image 21
Albin Sunnanbo Avatar answered Nov 01 '22 00:11

Albin Sunnanbo