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

3
  • 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. Commented May 27, 2016 at 15:37
  • A part of LINQ, you may want to read about StringBuilder. Commented May 27, 2016 at 15:38
  • @dlatikay I've added a 2nd query for SongDecoder(). Does that make it any different? Commented May 27, 2016 at 15:48

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.