0

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.

2 Answers 2

2

You can do it simply using this code:

var newLocationDevices = locationDevices
    .ToDictionary(
        o => o.Key,
        o => o.Value.Where(i => i.New).ToList()
    );
Sign up to request clarification or add additional context in comments.

5 Comments

'KeyValuePair<string, List<EquipmentRow>>' does not contain a definition for 'New'
@DomagojHamzic I had a typo which I've just fixed it. i=>i.New instead of 'o.New'
Will it filter Key value elements where New = false;?
@PrasadTelkikar As I understood the problem, only the inner list is needed to be filtered, not the outer one. Otherwise, another Where is needed just as you've mentioned.
What if inner list contains single element and it is New=false
1

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.

3 Comments

thanks, also correct answer but I can not mark >1 answer as correct :(
@DomagojHamzic But you can do a +1
this is slightly different the accepted answer, keys that would have an empty list are not going to be present in the dictionary in this version.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.