简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM