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

Time:06-08

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.

CodePudding user response:

You can do it simply using this code:

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

CodePudding user response:

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.
  • Related