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
Useful Tools
Online Code Editor and Compiler
HTML Minifier
Online HTML Compiler/Preivew
Word Count Tool
Replace Text/Word tool
Latest Blogs
How to check if a canvas is empty or blank
Maintain div or panel scroll position after postback in asp.net update panel
Draggable button using jquery ui
Get total number of tables, views, stored procedures and functions count and names in sql server
JavaScript function to get date in mmddyyyy hhmmss ampm forma