palak mehta
palak mehta

Reputation: 706

SubQuery using Lambda Expression

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

Upvotes: 0

Views: 1733

Answers (3)

EZI
EZI

Reputation: 15354

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);

Upvotes: 6

MacGyver
MacGyver

Reputation: 3073

This should help you:

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

Upvotes: 0

Thomas Lindvall
Thomas Lindvall

Reputation: 599

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));

Upvotes: 3

Related Questions