C
C#2y ago
novaleaf

❔ Tersest way to get (up to) last 3 elements in an array? (source array may have less than 3 items!)

Hello, trying to do something "simple", splitting a path string by \ and getting the last 3 folders:
var localFolders = filePath.Split('\\')[^3..];
var localFolders = filePath.Split('\\')[^3..];
The problem is this doesn't work if the Split() returns an array less than 3 long. I get an out of range exception) Is there some very terse work around that will get me the last 3 elements (or up to 3) of an array?
2 Replies
novaleaf
novaleafOP2y ago
I guess something like this would work,, but I hope there is something more terse you can come up with 🙂
var splits = filePath.Split('\\');
var localFolders = splits[^Math.Min(splits.Length,3)..]
var splits = filePath.Split('\\');
var localFolders = splits[^Math.Min(splits.Length,3)..]
cool that will work! 😄 much thanks I have to learn linq more 4sure
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