In this post, we’ll try to find the shortest word in a string using LINQ.
Given a string of words, return the length of the shortest word in the string.
Forget the edge cases of handling (empty or null).
Ex: “The shortest string” => should output 3 for “The”
So there will be a string which contains words. First, we’ll split that string with empty space so that we’ll get all the words in a string.
Now, we can sort the list of strings by length so that our shortest word will be in the first place and then we can perform a FirstOrDefault
on it.
public int ShortestWord(string s) { return s.Split(' ').OrderBy(x => x.Length).FirstOrDefault().Length; }
or we can do an orderby and then do a select the length and return the first item.
return s.Split(' ').OrderBy(i => i.Length).Select(i=>i.Length).First();
There can be many solutions like this.
Okay, we’ll see what’s the best or the clever solution
We have the .Min
extension method in LINQ. That should be sufficient to return the minimum length of the word.
public int ShortestWord(string s) { return s.Split(' ').Min(x => x.Length); }
That’s it! That will return the minimum length of a word in a string.
Karthik is a passionate Full Stack developer working primarily on .NET Core, microservices, distributed systems, VUE and JavaScript. He also loves NBA basketball so you might find some NBA examples in his posts and he owns this blog.
In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More
In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More
In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More
Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More
We saw how we could set up policy-based authorization in our previous article. In this… Read More
What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More
This website uses cookies.