0

What im trying to achieve, but cant get my head around is if i have a list of strings say:

{"test","","data","","123","44"}

this should be joined by a character:

test::data::123:44

but if the list at the end is empty dont delimiter it

{"test","","data","","",""}

should be:

test::data

{"test","","","","",""}

should be:

test

{"test","","","","","44"}

should be:

test::::44

however the list can be of varying lengths which adds another level of complexity.

Houlahan
  • 783
  • 3
  • 19
  • 46
  • Possible duplicate of [String.Join method that ignores empty strings?](http://stackoverflow.com/questions/16325995/string-join-method-that-ignores-empty-strings) – eugeneK Jul 08 '16 at 20:50
  • That's not what i'm looking for, because i don't want it to ignore empty strings i want it to only ignore trailing empty strings – Houlahan Jul 08 '16 at 20:51

4 Answers4

1

First, with your array:

test =  test.Where(x => !string.IsNullOrEmpty(x)).ToArray();

where "test" is your array.

then:

string.Join("::", test);

EDIT:

If you're getting your array of strings by splitting another string, consider the following:

string[] strs = myString.split(someDelimeter, StringSplitOptions.RemoveEmptyEntries);
S.Ahl
  • 69
  • 5
1
  var obj = {"test","","data","","123","44"};
  var count = obj.Count;

  for (var i = count - 1; i > -1; i--)
  {
    if (obj[i]==String.Empty) {
      obj.RemoveAt(i);
    }
    else break;
  }

  var arr = obj.Split(new char[] { ','}, StringSplitOptions.RemoveEmptyEntries);

  var output = arr.Join(":", arr);
Venkata Dorisala
  • 4,783
  • 7
  • 49
  • 90
  • my input isnt a JSON value its just a list of strings, its for EDIFACT D96a where trailing values don't require delimiters if the right most value is null – Houlahan Jul 08 '16 at 21:01
1

Start by identifying the last element you want, then slice your list and join as you normally would:

var lastElementIndex = strings.Select((s, index) => string.IsNullOrEmpty(s) ? -1 : index).Max();
var prefix = strings.Take(lastElementIndex + 1);
var result = string.Join(":", prefix);
Amit
  • 45,440
  • 9
  • 78
  • 110
1

Just exclude the trailing empty elements from the list Count and then Join the remaining using Take:

List<string> input = ...;
int count = input.Count;
while (count > 0 && string.IsNullOrEmpty(input[count - 1]))
    count--;
var output = string.Join(":", input.Take(count));

Using the List<T> specific FindLastIndex method, it can be reduced to the following "one liner":

var output = string.Join(":", 
    input.Take(input.FindLastIndex(s => !string.IsNullOrEmpty(s)) + 1));
Ivan Stoev
  • 195,425
  • 15
  • 312
  • 343
  • 1
    @Amit Right. But the question is tagged `list`, not `linq`. Which reminded me that there is a specific list method for that, so thank you :) – Ivan Stoev Jul 08 '16 at 22:58