Search code examples
c#linqcode-conversion

"System"-code to "System.Linq"-code


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.).


Solution

  • 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