string[] fruits = { "apple", "mango", "orange", "passionfruit", "grape" };
I want it not to take the last value in this string.
However, if there is only 1 value in the array, it may be an error if it does not take the last value as follows, so if there is 1 value in the array, it should take it. I want to put / between words. Is there an easy way to do this?
string[] fruits = { "apple" };
For example:
I output at string 1 : apple/mango/orange/passionfruit I got out on the 2nd string: apple
The last value in the 1st string is missing as you can see. but if 1 value remains in the string it should still show in the output
CodePudding user response:
string s = string.Join("/", fruits[fruits.Length > 1 ? ..^1 : ..]);
As per your edit 'the last value in the 1st string is missing as you can see' - I think this is the solution you need.
We use a Range object to return the desired values from the fruits array. We use a ternary operator to determine the behaviour - if there is more than one element we return all values except the last (Range ..^1), else we return all values (Range ..).
Finally we string.Join the result with "/" for the output you describe.
CodePudding user response:
This should work
string.Join('/', fruits.Take(1).Concat(fruits.Skip(1).Take(fruits.Length - 2)))
Here .Take(1)
makes sure that you always taking first element, fruits.Skip(1).Take(fruits.Length - 2)
excludes the last and first element (to not have duplicated first one) and .Concat
combines these into the correct result.
Might not be the best optimal way, but one liner without any conditions and checks