How to get first two words in a sentence using LINQ C# ?
If you are reading this article then I understand you google a lot to get solution. And you are on the right place. You can pick the Type 2 which is latest solution
In classic way to get this done is troublesome, and LINQ is the ultimate solution in one single line. This article explains the difference between two types of answers
Summary
This below method has too many lines of code and complicated, and look at the number of string declared memory occupying huge though it gives the correct result
This below method has too many lines of code and complicated, and look at the number of string declared memory occupying huge though it gives the correct result
Type 1
string output=string .Empty;
foreach (string s in sentence.Split(' ').Take(2))
{
output += s;
}
OUTPUT: MyName
This below method has ONLY one line of code
string sentence = "My Name is Hello Welcome!";
string strResult = string .Join("", sentence.Split(' ').Take(2));
OUTPUT: MyName
Process
Type 2
string strResult = string .Join("", sentence.Split(' ').Take(2));
OUTPUT: MyName
Step 1 : Sentence.Split(' ') splits the sentence by empty space which is ' '
Step 2 : Take(2) uses LINQ method, after spiting selects or takes only 2 words
Step 3: Now, if you debug your code results will be in array format, to return in a string format you need to use String.Join with empty space.
0 Comments