C
C#2y ago
answed

❔ ✅ Hey is there a way to check if something is in a list in a certain range from the list ?

Like for example i got a list of [2, 1,5, 6,3, 4, 1] and i want to see if there is a five in the list from position 4- 6 without using a for loop ?
18 Replies
Thinker
Thinker2y ago
You could do array[3..7].Contains(5)
MODiX
MODiX2y ago
thinker227#5176
REPL Result: Success
var xs = new[] {2, 1, 5, 6, 3, 4 ,1};
xs[3..6].Contains(4)
var xs = new[] {2, 1, 5, 6, 3, 4 ,1};
xs[3..6].Contains(4)
Result: bool
True
True
Compile: 570.448ms | Execution: 54.167ms | React with ❌ to remove this embed.
answed
answedOP2y ago
thx that was exactly what i was looking for ^^
Thinker
Thinker2y ago
np catsip
Pobiega
Pobiega2y ago
$close
MODiX
MODiX2y ago
Use the /close command to mark a forum thread as answered
Anton
Anton2y ago
that copied that part of the array, use AsSpan first arr.AsSpan()[3 .. 6].Contains(4)
ero
ero2y ago
well first, they said list
Anton
Anton2y ago
I don't think lists support slicing
ero
ero2y ago
that is correct
Anton
Anton2y ago
but you can get the span of a list
ero
ero2y ago
collectionsmarshal time
Anton
Anton2y ago
CollectionsMarshal.AsSpan or something like that or use linq, it also doesn't make copies
ero
ero2y ago
.Skip().SkipLast() or .Skip().Take()
Anton
Anton2y ago
but linq could be even worse for small lists in terms of memory
answed
answedOP2y ago
its a small list and this is used quite frequently so i dont know if a for loop is also a good solution bc of how small the list are (at most like 20 items but normally around 4- 9).
ero
ero2y ago
there is nothing better than a for loop for lists literally impossible to get any better the very best way is to use CollectionsMarshal.AsSpan, pin the resulting span, and work on that pointer unless the type is managed then you can't pin
Accord
Accord2y ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server