C# LINQ filter results based on property filed exist and value match

Viewed 149

Though there are plenty of examples available over internet, I am struggling with C# LINQ filtering. Below is my code and my expectation. Your help would be highly timely helpful. Thanks in advance.

I have the List with initial result set as below.

results = results.Where(item => String.Equals(item.Fields["name"].ToString(), "john", StringComparison.OrdinalIgnoreCase)).ToList();

I am trying to filter from results where all the result item has the field "name" and value "john". I am getting the error "The given key was not present in the Dictionary".

Reason for the error is, NOT all the item in the "results" has the field "name". Could you help me with how to get the result list that items has the field "name" and value "John"?

1 Answers

Update your condition inside Where and include item.Fields.ContainsKey("name") && . It will first check if dictionary has key name if yes then only it will try to compare.

results = results.Where(item => item.Fields.ContainsKey("name") && String.Equals(item.Fields["name"].ToString(), "john", StringComparison.OrdinalIgnoreCase)).ToList();
Related