I get fed JSON data and I need to create a varying amount of dictionaries to store events in. I can't seem to figure out or find and answer to something like this:
Creating a Dictionary:
foreach (Identity x in List.Identities)
{
Dictionary<int, int> shop + x.Id = new Dictionary<int, int>();
Dictionary<int, int> de + x.Id = new Dictionary<int, int>();
Dictionary<int, int> sell + x.Id = new Dictionary<int, int>();
}
So that later I can also input the varying number of events with max efficiency:
foreach (Event x in y.events)
{
if ((x.Type.Contains("PURCHASED")){
shop+x.Id.Add(x.timestamp, x.item);
}
if ((x.Type.Contains("SOLD")){
sell+x.Id.Add(x.timestamp, x.item);
}
if ((x.Type.Contains("DESTROYED")){
de+x.Id.Add(x.timestamp, x.item);
}
}
I know this is definitely NOT the way to declare these, but I can't find a way to have an int
variable declared in the dictionary name. If this works with lists, that would work as well, anything that I can foreach
. Thanks!
Here's the classes to avoid confusion:
public class Event
{
public string Type { get; set; }
public int timestamp { get; set; }
public int item { get; set; }
public int Id { get; set; }
}
public class ParticipantIdentity
{
public int Id { get; set; }
}
You don't. Variable names in C# are never dynamic - it sounds like you want a map from ID to "dictionary of timestamp to item".
In fact, I would probably create a separate type of ItemEvents
or something similar, which contained all the events for items with a single ID - e.g. by having three dictionaries within it.
You'd then just need:
var eventsByItem = List.Identities.GroupBy(x => x.Id)
.Select(g => new ItemEvents(g.Key, g))
.
where the ItemEvents
constructor would do the splitting, e.g.
public ItemEvents(int id, IEnumerable<Event> events)
{
this.id = id;
shops = events.Where(e => e.Type.Contains("PURCHASED"))
.ToDictionary(e => e.timestamp, e => e.item);
// Ditto for the other dictionaries.
}
As an aside, I would try to use a more meaningful type than int
for a timestamp - and consider using an enum
for the event type.
See more on this question at Stackoverflow