0

Let's say I have a string array like so

string[] arr = new {"a", "b", "\"b", "c\"", "c"};

I want to collapse these array into an array like so, while stripping the quotes.

{"a", "b", "b c", "c"}

How do I achieve this with a single LINQ line?

Mike
  • 826
  • 11
  • 31
  • 1
    "Most elegant" is subjective. The least overly complicated way would be manually with a for loop. – Abion47 Mar 08 '19 at 22:05
  • What have you tried? What is not working? How should it be changed to be more "elegant"? – Igor Mar 08 '19 at 22:07
  • I added extra details. How do I achieve this with a single LINQ line? – Mike Mar 08 '19 at 22:45
  • @Mike You aren't going to be able to do this with just a single line of LINQ calls. It's going to take some janky twists to get LINQ to do this at all. Why don't you want to just use a for loop? – Abion47 Mar 08 '19 at 23:05
  • Or while it *would* be feasible with a single line of LINQ, it would be really, really ugly. I would definitely expect a foreach loop building up the new list (which you can then turn into an array) to be simpler. The *first* step should be writing a lot of unit tests though. For example, inputs such as `{"a", "b", "\"b", "x", "c\"", "c"}` and `{"a", "b", "x\"b", "c\"y", "c"}`. I don't know at the moment what you'd expect the output to be in those cases - so you should decide that, and write tests. – Jon Skeet Mar 09 '19 at 08:23

1 Answers1

1

From your example, I assume that you want to recombine your array into a string with space as separator, then split it again, but refrain from splitting quoted substrings. Adapting the regex from this answer, this could be your solution:

string[] arr = new [] { "a", "b", "\"b", "c\"", "c" };
var result = Regex
    .Matches(string.Join(" ", arr), @"(?<match>[^\s""]+)|""(?<match>[^""]*)""")
    .Cast<Match>()
    .Select(m => m.Groups["match"].Value)
    .ToList();
Douglas
  • 53,759
  • 13
  • 140
  • 188