Domagoj Hamzic
Domagoj Hamzic

Reputation: 361

Using a Lambda Expression Over a Dictionary<string, List<object>> in C#

I have a dictionary that looks like this:

public Dictionary<string, List<EquipmentRow>> TableRows { get; set; }

EquipmentRow class:

public class EquipmentRow
{
    public string Model { get; set; }
    public bool New { get; set; }
}

I want to create/filter a structurally same Dictionary as the previous one which only contains a list of items in which property New is equal to true. How to achieve that by using a Lambda Expression? For example:

var newLocationDevices = locationDevices.Where(x => x.Value.Where()) etc.

Upvotes: 0

Views: 920

Answers (2)

mehrandvd
mehrandvd

Reputation: 9116

You can do it simply using this code:

var newLocationDevices = locationDevices
    .ToDictionary(
        o => o.Key,
        o => o.Value.Where(i => i.New).ToList()
    );

Upvotes: 2

Prasad Telkikar
Prasad Telkikar

Reputation: 16079

You can filter dictionary using .Where() clause and check bool value using .Any(),

var result = locationDevices
      .Where(x => x.Value.Any(x => x.New)) //Filter existing dictionary
      .ToDictionary(x => x.Key, x => x.Value.Where(y => y.New).ToList()); //Create new Dictionary.

Upvotes: 1

Related Questions