我想查询一个json文件以查找具有两个或多个共同标签的用户 [英] I want to query a json file to find users with two or more tags in common

查看:52
本文介绍了我想查询一个json文件以查找具有两个或多个共同标签的用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下json文件:

I have the following json file:

{
  "users": [
    {
      "tags": [
        "c++",
        "jquery",
        "css",
        "html"
      ],
      "name": "John Doe",
      "id": 0
    },
    {
      "tags": [
        "vb",
        "css"
      ],
      "name": "Bill Gates",
      "id": 1
    },
    {
      "tags": [
        "c++",
        "css",
        "html"
      ],
      "name": "Steve Jobs",
      "id": 3
    }
  ]
}

例如,我试图只返回与标签匹配两次或多次的用户:

I'm trying to return only users who match Tags twice or more, for instance:

John Doe和Steve Jobs有共同的c ++和css.

John Doe and Steve Jobs have c++ and css in common.

我试图通过执行大量的for语句来实现这一目标,但我认为这不是最好的解决方案.

I was trying to achieve this by performing tons of for statements but I don't think this is the best solution.

这就是我到目前为止所拥有的:

That's what I have so far:

JObject res = JObject.Parse(File.ReadAllText(@"C:/json/data.json"));
int jsonLength = res["users"].Count();
for (int i = 0; i < jsonLength; i++)
{
    string name = res["users"][i]["name"].ToString();
    int id = Convert.ToInt32(res["users"][i]["id"]);
    string tags = res["users"][i]["tags"].ToString();

    Console.WriteLine("ID: " + id);
    Console.WriteLine("Name: " + name);
    Console.WriteLine("Tags: " + tags);
}

我看到有些人像在SQL中一样查询json文件,但是我以前从未使用过LINQ,所以我不知道它是如何工作的,我也不知道什么是实现此目的的最佳方法.

I saw some people querying a json file like they do in SQL but I've never used LINQ before so I have no idea on how it works also I'm not sure what's the best way to approach this.

推荐答案

如果只想与其他用户共享两个或多个标签的所有用户的列表,则可以执行以下操作:

If you just want a list of all users that share two or more tags with another user, you could do something like this:

string json = File.ReadAllText(@"C:\json\data.json");
JArray users = (JArray)JObject.Parse(json)["users"];

// Generate pair-wise combinations of users
// and check for intersection of their tags.
// If two or more common tags, add both users to a hash set

HashSet<JObject> result = new HashSet<JObject>();
for (int i = 0; i < users.Count; i++)
{
    JObject user1 = (JObject)users[i];
    for (int j = i + 1; j < users.Count; j++)
    {
        JObject user2 = (JObject)users[j];
        if (user1["tags"].Select(t => t.ToString())
            .Intersect(user2["tags"].Select(t => t.ToString()))
            .Count() > 1)
        {
            result.Add(user1);
            result.Add(user2);
        }
    }
}

Console.WriteLine("All users that share two or more tags with another user:");
Console.WriteLine();

foreach (JObject user in result)
{
    Console.WriteLine("id: " + user["id"]);
    Console.WriteLine("name: " + user["name"]);
    Console.WriteLine("tags: " + string.Join(", ", user["tags"]));
    Console.WriteLine();
}

提琴: https://dotnetfiddle.net/IpZBIR

如果要查看每对用户以及他们之间的公共标签,则需要更多代码来捕获配对.首先,我将创建几个类来使数据更易于使用:

If you want to see each pair of users along with the common tags between them, you need a little more code to capture the pairings. First, I would create a couple of classes to make the data easier to work with:

class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<string> Tags { get; set; }
}

class Pairing
{
    public User User1 { get; set; }
    public User User2 { get; set; }
    public List<string> CommonTags { get; set; }
}

然后您可以像这样捕获配对:

Then you can capture the pairings like this:

string json = File.ReadAllText(@"C:\json\data.json");

// Parse the JSON into a list of Users

List<User> users = JObject.Parse(json)["users"]
   .Select(t => t.ToObject<User>())
   .ToList();

// Generate pair-wise combinations of users
// and check for intersection of their tags.
// If two or more common tags, add the pairing to a list

List<Pairing> pairings = new List<Pairing>();
for (int i = 0; i < users.Count; i++)
{
    User user1 = users[i];
    for (int j = i + 1; j < users.Count; j++)
    {
        User user2 = users[j];
        var commonTags = user1.Tags.Intersect(user2.Tags).ToList();

        if (commonTags.Count > 1)
        {
            pairings.Add(new Pairing
            {
                User1 = user1,
                User2 = user2,
                CommonTags = commonTags
            });
        }
    }
}

// Write out the results

Console.WriteLine("Pairs of users sharing two or more tags with each other:");
Console.WriteLine();

foreach (Pairing p in pairings)
{
    Console.WriteLine(string.Format("{0} (id {1}) and {2} (id {3}) have ({4}) in common.",
     p.User1.Name, p.User1.Id, p.User2.Name, p.User2.Id, string.Join(", ", p.CommonTags)));
}

提琴: https://dotnetfiddle.net/vQlJSV

这篇关于我想查询一个json文件以查找具有两个或多个共同标签的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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