How to join and perform an operation between JSON data in C#?

I'm dealing with linq-to-entities, querying 2 different entities. One returns data and the other returns addValues, also I have references to both NewtonSoft.Json and System.Data.Objets: var query1 returns data and var query2 returns addValues. Debugging I can see that:

data = [{"key":"tf","value":221},{"key":"ba","value":108}];

addValues = [{"key":"tf","value":2},{"key":"ba","value":1.5}];

How do I obtain a new string/object joining by "key" and performing an operation between the values from data and addValues? The result of the query should be calculatedResult.

result = [{"key":"tf","value":221+2},{"key":"ba","value":108+1.5}];

calculatedResult = [{"key":"tf","value":223},{"key":"ba","value":109.5}];

Important note: I can be sure that both arrays will have the same number of items, BUT not ordered by key

Upvotes: 1

Views: 172

Answers (1)

Mark Segal
Mark Segal

Reputation: 5550

The following snippet will work, assuming that each element in data and addValues has both a key and value field.

public class Foo
{
    public string key;
    public float value;
}
class Program
{
    static void Main(string[] args)
    {
        var data = "[{\"key\":\"tf\",\"value\":221},{\"key\":\"ba\",\"value\":108}]";
        var addValue = "[{\"key\":\"tf\",\"value\":2},{\"key\":\"ba\",\"value\":1.5}]";

        var obj1 = JsonConvert.DeserializeObject<List<Foo>>(data);
        var obj2 = JsonConvert.DeserializeObject<List<Foo>>(addValue);
        var new_obj = (from a in obj1
                       from b in obj2
                       where a.key == b.key
                       select new Foo { key = a.key, value = a.value + b.value }).ToList();
        Console.WriteLine(JsonConvert.SerializeObject(new_obj, Formatting.Indented));

    }
}

Output:

[
  {
    "key": "tf",
    "value": 223.0
  },
  {
    "key": "ba",
    "value": 109.5
  }
]

Upvotes: 1

Related Questions