Reputation: 189
I have a Dictionary<string, string> object that has the following template of values:
Key = "data[0][name]" | Value = "Test"
Key = "data[0][type]" | Value = "Type Test"
Key = "data[0][description" | Value = "Description Test"
Key = "data[1][name]" | Value = "Test"
Key = "data[1][type]" | Value = "Type Test"
Key = "data[1][description" | Value = "Description Test"
Key = "data[2][name]" | Value = "Test"
Key = "data[2][type]" | Value = "Type Test"
Key = "data[2][description" | Value = "Description Test"
How can I parse this dictionary into their own objects with the values Name, Type, Description?
Upvotes: 0
Views: 309
Reputation: 507
Similar alternative:
using System;
using System.Linq;
using System.Collections.Generic;
//...
public struct DataItem
{
public string name;
public string type;
public string description;
}
//...
public List<DataItem> CustomFn(Dictionary<string,string> dict)
{
var list = new List<DataItem>();
int size = dict.Count/3;
for(int i=0; i<size; ++i)
{
Func<string,string> t = (key) => {
var dictkey = $"data[{i}][{key}]";
return dict.ContainsKey(dictkey) ? dict[dictkey] : null;
};
list.Add(new DataItem() {
name = t("name"),
type = t("type"),
description = t("description"),
});
}
return list;
}
update: check if key exists in dictionary
Upvotes: 0
Reputation: 416039
First you need to declare your class type:
public class MyItem
{
public string Name {get;set;}
public string Type {get; set;}
public string Description {get;set;}
}
If you were hoping to infer the type, that's technically possible using, say, a JSON or Tuple result, or maybe even generators or codegen/dynamic IL. But it's not really how .Net is made to work.
Then you can do something like this:
public IEnumerable<MyItem> GetItems(Dictionary<string, string> items)
{
// This assume every property is always populated
int numItems = items.Count / 3; // 3 is the number of properties.
for(int i = 0;i<numItems;i++)
{
yield reutrn new MyItem() {
Name = items[$"data[{i}][name]"],
Type = items[$"data[{i}][type]"],
Description = items[$"data[{i}][description]"]
};
}
}
If you can't infer how many items you might have based on the size of the dictionary alone, you're gonna have to parse out each item in the dictionary's Keys
property to figure it out. The same it true if you're not sure in advance what your properties will be.
Upvotes: 2