LINQ basic string and digit operations
Hi, today I want to show you how we can do the basic string and digit operations with the LINQ. If you are not using Linq in your current projects, you may find it very tempting to start with it. Once you learn it you will probably be using it all the time 🙂
Lets start with the function that sums the numbers that contains a given digit. We can do it in just one line of code 🙂
public static int SumNumbers(int[] numbers, int digit) { return numbers.Where(i => i.ToString().Contains(digit.ToString())).Sum(); }
If you want to sum number of words that contain minimum number of letters, this will be useful.
public static int CountWords(string text, int minNumberOfLetters) { return text.Split(' ').Count(i => i.Length >= minNumberOfLetters); }
If you ever wanted to find the longest word in a text, here is example.
public static string FindLongestWord(string text) { return text.Split(' ').OrderByDescending(i => i.Length).ThenBy(i => i).First(); }
And if you want to count number of distinct words longer than given number, check this
public static int CountWordsLongerThan(string text, int minimumLetters) { return text.Split(' ').Where(i => i.Length >= minimumLetters).Distinct().Count(); }
This function gets list of non unique words in the string (separated by the space) and longer than 5 letters
public static IEnumerable<string> FindNonUniqueWords(string inputText) { return inputText.ToLower().Split(' ') .OrderBy(i => i).GroupBy(i => i).Where(i => i.Count() > 1) .Select(i => i.Key).Where(i => i.Length > 5); }
And finally something more sophisticated, similarity calculation between two texts (for words having more than 4 letters)
public static int CalculateSimilarity(string text1, string text2) { var words1 = text1.Split(' ').Where(i => i.Length > 4).Distinct(); var words2 = text2.Split(' ').Where(i => i.Length > 4).Distinct(); return words1.Intersect(words2).Count(); }
Don’t forget to use “using System.Linq;” namespace in your project before using this. And of course parameters validation must be added to every function to be fully functional.
That’s it for now.