Using struct in dictionary as a value

Anand unnikrishnan 1 Reputation point
2022-10-16T05:33:32.63+00:00

Hi I have a struct and dictionary as below and I'm trying to add it as a custom value like

public struct data_inv
{
//protected static int p;
public float inventory;
public float supply;
public float demand;
};
public static IDictionary<int, data_inv> inv_stored = new Dictionary<int, data_inv>();
and I have tried to add value to dictionary but when I try to add a value like inv_stored[1].demand = 4; its gives System.Collections.Generic.KeyNotFoundException: 'The given key was not present in the dictionary.' exception. I'm new to coding, could any explain what im doing wron

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,389 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 113K Reputation points
    2022-10-16T07:58:25.61+00:00

    To add a new item:

    inv_stored[1] = new data_inv { demand = 4 };

    To modify the existing item:

    data_inv d = inv_stored[1];
    d.demand = 5;
    inv_stored[1] = d;

    1 person found this answer helpful.
    0 comments No comments