C
C#17mo 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
Thinker17mo ago
You could do array[3..7].Contains(5)
MODiX
MODiX17mo 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
answed17mo ago
thx that was exactly what i was looking for ^^
Thinker
Thinker17mo ago
np catsip
Pobiega
Pobiega17mo ago
$close
MODiX
MODiX17mo ago
Use the /close command to mark a forum thread as answered
Anton
Anton17mo ago
that copied that part of the array, use AsSpan first arr.AsSpan()[3 .. 6].Contains(4)
ero
ero17mo ago
well first, they said list
Anton
Anton17mo ago
I don't think lists support slicing
ero
ero17mo ago
that is correct
Anton
Anton17mo ago
but you can get the span of a list
ero
ero17mo ago
collectionsmarshal time
Anton
Anton17mo ago
CollectionsMarshal.AsSpan or something like that or use linq, it also doesn't make copies
ero
ero17mo ago
.Skip().SkipLast() or .Skip().Take()
Anton
Anton17mo ago
but linq could be even worse for small lists in terms of memory
answed
answed17mo 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
ero17mo 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
Accord17mo 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
More Posts