Home > DeveloperSection > Forums > How to use LINQ to separate a list element and inserting the results back to list
Chintoo Semi

Total Post:135

Points:947
Posted on    January-26-2015 10:41 PM

 ASP.Net C#  LINQ  ListView 
Ratings:


 1 Reply(s)
 521  View(s)
Rate this:

I have a list of strings like this(""Joe", "wants", "to", "thank", "you!"") what I want is to separate "you", "!" and """ and insert them back to that list using LINQ. I know there are many LINQ experts here, which can do it in a minute. What I'm doing is separating a sentence into words:

    string sentence = "\"Joe wants to thank you!\"";

    string[] words = sentence.split(" ");

    List<string> result = new List<string>();

 

    for (int i = 0; i < words.Length; i++)

    {

        string word = words[i];

        if (word.EndsWith("."))

        {

            result.Add(word.Substring(0, word.LastIndexOf(".")));

            result.Add(".");

        }

        else if (word.EndsWith("..."))

        {

            result.Add(word.Substring(0, word.LastIndexOf("...")));

            result.Add("...");

        }

        else if (word.EndsWith(","))

        {

            result.Add(word.Substring(0, word.LastIndexOf(",")));

            result.Add(",");

        }

        else if (word.EndsWith("\""))

        {

            result.Add(word.Substring(0, word.LastIndexOf("\"")));

            result.Add("\"");

        }

 

 

     }

The problem is with sentence that ends with !"NOTE: words is the array splitted by space.

 



john rob

Total Post:108

Points:756
Posted on    January-27-2015 12:14 AM

since you are already splitting it by spaces, just replace and add a space before splitting up

sentence = sentence.Replace("!", " !");

I don't think you need linq but something kind of elegant for you would be

var addMyspace = new List<string>{"!", "...", "\"", ".", ","};

 

foreach(var s in addMyspace)

{

     sentence = sentence.Replace(s, string.Format(" {0}",s));

}

//split


Don't want to miss updates? Please click the below button!

Follow MindStick