C#

Shortest word in a string with LINQ

In this post, we’ll try to find the shortest word in a string using LINQ.

Problem

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”

Initial thoughts

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

Best 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.

Disqus Comments Loading...
Share
Published by
Karthik Chintala
Tags: linq

Recent Posts

2 Good Tools To Test gRPC Server Applications

In this post, we’ll see how to test gRPC Server applications using different clients. And… Read More

1 year ago

Exploring gRPC project in ASP.NET Core

In this post, we'll create a new gRPC project in ASP.NET Core and see what's… Read More

2 years ago

Run dotnet core projects without opening visual studio

In this blog post, we’ll see how to run dotnet core projects without opening visual… Read More

2 years ago

Programmatically evaluating policies in ASP.NET Core

Programmatically evaluating policies is useful when we want to provide access or hide some data… Read More

2 years ago

Multiple authorization handlers for the same requirement in ASP.NET Core

We saw how we could set up policy-based authorization in our previous article. In this… Read More

2 years ago

Policy-Based Authorization in ASP.NET Core

What is policy-based authorization and how to set up policy-based authorization with handlers and policies… Read More

2 years ago

This website uses cookies.