0

I am using a LINQ subquery to obtain all the words of minimum length in an array. I want to do it using Lambda Expression.

var names = new[] { "Tom", "Dick", "Harry", "Mary", "Jay" }.AsQueryable();
(
from n in names
where n.Length == names.Min (n2 => n2.Length)
select n
)

Output : Tom , Jay

Thanks, Prakhar

3 Answers 3

6

This would work:

var minNames = names.Where(s => s.Length == names.Min(n=>n.Length));

But it evaluates the min length for every name in list (O(n*n) complexity), therefore this would be better:

var min = names.Min(s => s.Length); //calc. this only once
var minNames = names.Where(s => s.Length == min);
Sign up to request clarification or add additional context in comments.

1 Comment

Upvoted. See the interesting linked thread which confirms that Min method is called each time, leading to O(n**2) complexity just like you say. Another way to tackle this is int min = int.MaxValue; var minNames = names.OrderBy(s => s.Length).TakeWhile(s => min >= (min = s.Length)) but that is hardly better than your solution.
3

The question to me seems a little bit vague, but is this what you're looking for?

 names.Where (x => x.Length == names.Min (n2 => n2.Length));

Comments

0

This should help you:

    var minNames = names.Where(c => c.Length == names.Min(n => n.Length))
            .ToArray();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.