0

I am incredibly new to LINQ, in fact... I'm so new I just figured out that everything before the dot is given through to the called method.

using System;

public class Program
{
    public static void Main()
    {
        Console.WriteLine(SongDecoder("WUBWUBABCWUB"));
        Console.WriteLine(SongDecoder("RWUBWUBWUBLWUB"));
    }

    public static string SongDecoder(string input)
    {
      string[] s = input.Split(new string[] { "WUB" }, StringSplitOptions.RemoveEmptyEntries);

      string reStr = "";
      for (int i = 0; i < s.Length; i++)
        if(i == s.Length - 1)
          reStr += s[i];
        else
          reStr += s[i] + " ";

      return reStr;
    }
}

I'm wondering how I can convert this to a "simple" LINQ variant and if it'd be faster with LINQ (As I heard great and fast things about LINQ.).

sxbrentxs
  • 93
  • 7
  • could you add a sampe value for `input` so we can get an idea of what you're trying to achieve? LINQ is not something specifically designed to optimize string manipulation/concatenation in first place, so there might be other options. Most of the work here seems to be concatenation, so consider using a `StringBuilder` for the `reStr` variable. – Cee McSharpface May 27 '16 at 15:37
  • A part of LINQ, you may want to read about [StringBuilder](https://msdn.microsoft.com/en-us/library/system.text.stringbuilder(v=vs.110).aspx). – aloisdg May 27 '16 at 15:38
  • @dlatikay I've added a 2nd query for SongDecoder(). Does that make it any different? – sxbrentxs May 27 '16 at 15:48

1 Answers1

4

No LINQ needed here

var reStr =  String.Join(" ", 
               input.Split(new string[] {"WUB"}, StringSplitOptions.RemoveEmptyEntries));

Sorry :( LINQ is very useful though, I suggest you read about it.


Ok, I conceed, if you really want to use LINQ there is always Aggregate

var retStr = input.Split(new string[] {"WUB"}, StringSplitOptions.RemoveEmptyEntries))
                  .Aggregate ( (a,b) => a + " " + b);

read more here: LINQ Aggregate algorithm explained

Community
  • 1
  • 1
Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • Just remember LINQ might not always be the best choice, because it can sometime decrease performance. In some cases a simple loop might perform better. – Bauss May 27 '16 at 16:11