Menu ▼

Previous Next

LINQ to Strings :

In this example we will write LINQ queries on string to find distinct words in the string and duplicate words in the string .

LINQ Query :
Below query will split the string into words order by words length.

string input = "linq to        string              example";

var wordsorderbylength = from str in input.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)

                            orderby str.Length

                            select new { WordsOrderByLength = str };

gvLength.DataSource = wordsorderbylength;

gvLength.DataBind();


Output :
WordsOrderByLength
to
linq
string
example

LINQ Query :
Below query will find the distinct words in the string order by words.

string input1 = "hi Hellow HI world hellow world world hi hi";

var wordsuinque = from str in input1.ToLowerInvariant().Split().Distinct()

                    select new { DistinctWords = str };

gvUniqueWords.DataSource = wordsuinque;

gvUniqueWords.DataBind();


Output :
DistinctWords
hi
hellow
world

LINQ Query :
Below query will find the duplicate words in the string order by words.

string input2 = "This sentance contains duplicate words and the following linq query will find the duplicate words in this sentance";

var duplicatewords = from str in input2.ToLowerInvariant().Split()

                        group str by str into temp

                        orderby temp.Key

                        where temp.Count() > 1

                        select new { DuplicateWords = temp.Key };

gvDuplicateWords.DataSource = duplicatewords;

gvDuplicateWords.DataBind();


Output :
DuplicateWords
duplicate
sentance
the
this
words

Previous Next




Search dotnetlearners.com