geejay
geejay

Reputation: 5618

Lambda expression to grab all values inside a Dictionary

I have a LINQ query which returns all the values inside a Dictionary, conditional upon something:

var apps =
from entry in shape.Decorators
where entry.Value == DecoratorLayoutStyle.App
select entry.Key;

shape.Decorators is a

Dictionary<Shape, DecoratorLayoutStyle>

Is there something terser, and/or can I use a combination of lambdas or something?

Upvotes: 2

Views: 5020

Answers (5)

R. Martinho Fernandes
R. Martinho Fernandes

Reputation: 234604

var apps = shape.Decorators
                     .Where(e => e.Value ==  DecoratorLayoutStyle.App)
                     .Select(e => e.Key);

Do you think this is terser?

Personally I prefer the query syntax when I have more than one LINQ operator all the operators I use can be translated to it.

Upvotes: 2

Amy B
Amy B

Reputation: 110171

Just to be different.

var apps = shape.Decorators.Keys
  .Where(k => shape.Decorators[k] == DecoratorLayoutStyle.App);

Upvotes: 0

user1228
user1228

Reputation:

var apps = shape.Decorators
                .Where(x=>x.Value == DecoratorLayoutStyle.App)
                .Select(x=>x.Key);

I think yours is just as fine.

Upvotes: 6

brien
brien

Reputation: 4440

That looks plenty terse to me, I guess you could use the extension functions instead of the from/select linq syntax, but that wouldn't be too different.

More imporantly, I'm not sure you want terser. The current format is very readable, and clearly documents exactly what you're trying to do.

Upvotes: 3

Mehrdad Afshari
Mehrdad Afshari

Reputation: 422132

var apps = Shape.Decorators.Where(x => x.Value == DecoratorLayoutStyle.App)
                           .Select(x => x.Key);

Upvotes: 1

Related Questions