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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With