我正在尝试通过字典键和值搜索包含列表
下面是我的 Json 联系人数组
[
{
"first_name": "David",
"last_name": "Smith",
"email": "[email protected]",
"phone": "1234567890",
"website": "google.com",
"relations": [
{
"listid": "65512fe1e759b98f40b48829"
},
{
"listid": "34212fe1e759b98f40b48829"
}
]
},
{
"first_name": "Chris",
"last_name": "Oven",
"email": "[email protected]",
"phone": "1234567890",
"website": "google.com",
"relations": [
{
"listid": "65512fe1e759b98f40b48829"
},
{
"listid": "34212fe1e759b98f40b48829"
}
]
}
]
我正在尝试查找包含 listid =“65512fe1e759b98f40b48829”的所有联系人。
使用 Linq 执行此操作的最佳方法是什么?
尝试了如下所示:
var searchPair = new KeyValuePair<string, string>("listid", "65512fe1e759b98f40b48829");
contacts.Where(p=>p.relations.Where(dictionary => dictionary[searchPair.Key].ToString().Contains(searchPair.Value)).ToList();
但是在某个地方它给出了错误的搜索方式
在我看来,这是 JSON 的更好表示:
public class Customer
{
[JsonProperty("first_name")]
public string FirstName { get; set; }
[JsonProperty("last_name")]
public string LastName { get; set; }
[JsonProperty("email")]
public string Email { get; set; }
[JsonProperty("phone")]
public string Phone { get; set; }
[JsonProperty("website")]
public string Website { get; set; }
[JsonProperty("relations")]
public List<Relation> Relations { get; set; }
}
public class Relation
{
[JsonProperty("listid")]
public string ListId { get; set; }
}
现在您可以读入您的数据:
List<Customer> customers =
Newtonsoft
.Json
.JsonConvert
.DeserializeObject<List<Customer>>(
File.ReadAllText(@"customers.json"));
这给出了:
现在查询就简单了:
IEnumerable<Customer> query =
from c in customers
where c.Relations.Any(r => r.ListId == "65512fe1e759b98f40b48829")
select c;