BadmintonCat
BadmintonCat

Reputation: 9576

Get a list of specific values from a C# Dictionary

Let's say I have a C# dictionary with Enum values like this:

public enum TileType
{
    Source,
    Horizontal,
    Vertical
}

Dictionary<Tile, TileType> tiles = new Dictionary<Tile, TileType>();

... And later I want to retrieve all key value pairs from the dict that are for example of value = TileType.Horizontal but without using a foreach loop.

How do I retrieve them without a loop? I have no doubt it's possible with LINQ. Can somebody give me a hint how to write the LINQ for that?

Upvotes: 1

Views: 114

Answers (5)

G.Mich
G.Mich

Reputation: 1666

 foreach (var item in tiles.Where(t => t.Value == TileType.Horizontal))
 {
     Console.WriteLine(item.Key);
 }

Upvotes: 0

goodday21
goodday21

Reputation: 53

I would write something like that:

tiles.Where(t => t.value == TileType.Horizontal).ToArray();

Upvotes: 0

Anup Sharma
Anup Sharma

Reputation: 2083

Its like this:

var filteredTiles = tiles.Where(x=>x.Value == TileType.Horizontal);

Upvotes: 0

Ric
Ric

Reputation: 13248

Use this:

tiles.Where(x => x.Value == TileType.Horizontal);

Upvotes: 0

Enigmativity
Enigmativity

Reputation: 117029

Try this:

var horizontals = tiles.Where(kvp => kvp.Value == TileType.Horizontal).ToList()

Upvotes: 4

Related Questions