Home > Net >  How to compare 3 different Lists & get the value in c#
How to compare 3 different Lists & get the value in c#

Time:10-20

I send below request & receive the below response. but in response model only Index is the item identifier, there is no itemcode.

I want to update the discount details of each product in the database, how can I do this.

P.S I am already having all necessary c# classes for database & other stuff, just help me with getting discount details for each item. Please help me with whatever that needs write for this like joins, linq, loops..

Request:

  "Items": [
    {
      "itemcode": 5,
      "price": 600,
      "Index": 1
    },
    {
      "itemcode": 34,
      "price": 970,
      "Index": 2
    }
  ]
}

**Response:**

{
  "Items": [
    {
      "discount": {
        "id": 3,
        "amoumt": 40
      },
      "Index": 1
    },
    {
      "discount": {
        "id": 3,
        "amoumt": 25
      },
      "Index": 2
    }
  ]
}


**Finally it should look like**
{
  "items": [
    {
      "itemCode": 5,
      "discount": {
        "id": 3,
        "amoumt": 40
      }
    },
    {
      "itemCode": 34,
      "discount": {
        "id": 3,
        "amoumt": 25
      }
    }
  ]
}

CodePudding user response:

I'm understanding that you need to pair each request item with it's corresponding response item, since you need information from both to do the DB update. There are multiple ways to achieve this. On is using Join():

IEnumerable<(RequestItem, ResponseItem)> pairs = request.Items.Join(
    response.Items,
    reqItem => reqItem.Index,
    resItem => resItem.Index,
    (reqItem, resItem) => (reqItem, resItem));

This gives you an enumerable of request/response item pairs that you can iterate over in a list to perform the update.

CodePudding user response:

try this code, you can replace anonymous class with yours

    var items1 = (JArray)JObject.Parse(json1)["Items"];
    var items2 = (JArray)JObject.Parse(json2)["Items"];

    var query = from i1 in items1
                 join i2 in items2
                 on (int)i1["Index"] equals (int)i2["Index"]
                 select  new
                 {
                     ItemCode = (int)i1["itemcode"],
                     Discount = new
                     {
                         Id = (int)i2["discount"]["id"],
                         Amount = (int)i2["discount"]["amoumt"],
                     }
                 };
     var items = new { Items = query };

test

string json =   JsonConvert.SerializeObject(items, Newtonsoft.Json.Formatting.Indented);

{
  "Items": [
    {
      "ItemCode": 5,
      "Discount": {
        "Id": 3,
        "Amount": 40
      }
    },
    {
      "ItemCode": 34,
      "Discount": {
        "Id": 3,
        "Amount": 25
      }
    }
  ]
}
  • Related