HOW TO USE LINQ TO SEPARATE A LIST ELEMENT AND INSERTING THE RESULTS BACK TO LIST

Chintoo Semi

Total Post:135

Points:947
Posted by  Chintoo Semi
C#  LINQ  ListView 
 1032  View(s)
Ratings:
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.

 

  1. john rob

    Post:108

    Points:756
    Re: How to use LINQ to separate a list element and inserting the results back to list

    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

      Modified On Apr-09-2018 12:01:47 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!