LINQ-反序列化JSON列和过滤器 [英] LINQ - Deserialize JSON column and filter

查看:55
本文介绍了LINQ-反序列化JSON列和过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用JSON字符串数组值反序列化/序列化属性,然后在lamq表达式内的LINQ中进行过滤(使用where子句)?

How to deserialize/serialize a property with JSON string array value and then filter (using where clause) in LINQ inside a lambda expression?

void Main()
{
    var regionList = new List<Row>() {
        new Row { RegionJsonList = "[\"QLD\",\"NSW\"]" },
        new Row { RegionJsonList = "[\"TAZ\",\"SA\"]" },
        new Row { RegionJsonList = "[\"QLD\",\"VIC\"]" }
    };

    var filterRegionList = new List<string>() {
        "QLD", "NSW"
    };

    var queryable = regionList.AsQueryable();


    // this is obviously wrong, i just want to find the Row that contains one on filterRegionList
    var result = queryable.Where(r => JsonConvert.DeserializeObject<string[]>(r.RegionJsonList).Contains(filterRegionList));

    result.Count().Dump(); // should be 2

}

class Row
{
    public string RegionJsonList { get;set; }
}

推荐答案

以下方法将起作用:

var result =
filterRegionList.Aggregate(regionList,(current,filter) => 
current.Where( r => r.RegionJsonList.Contains(filter)).ToList())

汇总filterRegionListregionList,从而为最终结果应用过滤器.我没有发现反序列化RegionJsonList的要求,因为它可以照常工作,但是如果您热衷于此,可以添加该部分.

Aggregating the filterRegionList and regionList and thus applying filters for the final result. I did not find a requirement to Deserialize the RegionJsonList, since this would work as is, but you may add that part in case you are keen.

此外,我们通过聚合应用And过滤器,它检查包含两个过滤器的行,从而提供结果,您可以修改过滤器以实现更多的行数,例如以下将从原始内容中选择两个条目regionList

Also we are applying And filter via aggregation, it checks for the rows which contains both the filters, and thus provide the result, you may modify filter to achieve more number of rows, like following will select two entries from original regionList

var filterRegionList = new List<string>() { "QLD"  };

这篇关于LINQ-反序列化JSON列和过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆