Search code examples
c#linqjson.net

Filter deserialized results on a specific value from array of JSON objects?


I am getting JSON responses from API:

"table1": [
    {
        "abc": "test",
        "def": "test1"
    },
    {
        "abc": "test2",
        "def": "User1"
    }       
]

which is binding into

public List<object>? table1 { get; set; }

I want to get the User1 using Linq/Lamda. Below returns 0 record:

    var filteredList = table1
        .Where(item => 
        item.GetType().GetProperty("def",BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase)?.GetValue(item)?.ToString() is "User1" or "User2")
.ToList();

What is wrong with it


Solution

  • I don't see why you attempt with System.Reflection and pattern matching is here.

    Either with the help of the JSON library such as Newtonsoft.Json to read/parse the object's field:

    using Newtonsoft.Json.Linq;
    
    string[] filters = new string[] {"User1", "User2"};
    var filteredList = table1
        .Where(item => filters.Contains(JObject.FromObject(item)?.SelectToken("def").ToString()))
        .ToList();
    

    Or if you know the structure of your Table object, you define and use the model class instead of object type:

    public class Root
    {
        public List<Table>? table1 { get; set; }
    }
    
    public class Table
    {
        public string Abc { get; set; }
        public string Def { get; set; }
    }
    
    string[] filters = new string[] {"User1", "User2"};
    var filteredList = table1
        .Where(item => filters.Contains(item.Def))
        .ToList();