yarek
yarek

Reputation: 12054

How to store objects in List or Dictionary (JS way)?

I am new to C# I want to store some simple objects in a associative array, JS like

var part["part1"] = {id:1, name:"part 1 ", posX:100, posY:200};
var part["part2"] = {id:2, name:"part 2 ", posX:300, posY:250};

and then retrieve that easily with

name = "part2"
print(part[name].x);

I had a look at: NameValueCollection, but it looks I can store simple values there only.

I tried with Collections and structures: which looks quite big and heavy just to store some simple values.

Is there a better/quicker/simpler way?

Upvotes: 1

Views: 208

Answers (3)

Nguyễn Văn Phong
Nguyễn Văn Phong

Reputation: 14228

You should use Dictionary

For example

var part = new Dictionary<string, object>();
part.Add("part1", new { id = 1, name = "part 1 ", posX = 100, posY = 200});
part.Add("part2", new { id = 2, name = "part 2 ", posX = 300, posY = 250});

var result = part["part1"];
Console.WriteLine(result);

The live demo here


Updated

If you want to access the property in C#, you should declare Specify Class. This is simply because, C# is strong type whereas Javascript is weak type

As a result, you can see the sample below to more understand

public static void Main()
{
    var persons = new Dictionary<string, Person>();
    persons.Add("Phong", new Person { Id = 1, Name = "Phong"});
    persons.Add("Nguyen", new Person { Id = 1, Name = "Nguyen"});

    var result = persons["Phong"];
        Console.WriteLine("ID: " + result.Id + " Name: " + result.Name);
        // Output: ID: 1 Name: Phong
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Live demo here

Upvotes: 2

Mario Vernari
Mario Vernari

Reputation: 7294

C# does not allow you the "freedom" you have in JavaScript. So, you should create a specific type for what the map will hold. I know, that is sometimes not comfortable.

Another approach is to leverage the NewtonSoft.JSON library (JLinq section), then use a Dictionary<string, JObject> to hold JSON "nodes":

string json = @"{
  'channel': {
    'title': 'James Newton-King',
    'link': 'http://james.newtonking.com',
    'description': 'James Newton-King\'s blog.',
    'item': [
      {
        'title': 'Json.NET 1.3 + New license + Now on CodePlex',
        'description': 'Announcing the release of Json.NET 1.3, the MIT license and the source on CodePlex',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'categories': [
          'Json.NET',
          'CodePlex'
        ]
      },
      {
        'title': 'LINQ to JSON beta',
        'description': 'Announcing LINQ to JSON',
        'link': 'http://james.newtonking.com/projects/json-net.aspx',
        'categories': [
          'Json.NET',
          'LINQ'
        ]
      }
    ]
  }
}";

JObject rss = JObject.Parse(json);

string rssTitle = (string)rss["channel"]["title"];
// James Newton-King

string itemTitle = (string)rss["channel"]["item"][0]["title"];
// Json.NET 1.3 + New license + Now on CodePlex

JArray categories = (JArray)rss["channel"]["item"][0]["categories"];
// ["Json.NET", "CodePlex"]

IList<string> categoriesText = categories.Select(c => (string)c).ToList();
// Json.NET
// CodePlex

Upvotes: 0

Prasad Telkikar
Prasad Telkikar

Reputation: 16069

You can create class which will store all properties like id, name, posX, posY. To associate this class with part name you can use dictionary.

Structure will look like,

public class Location
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int PosX {get; set;}
    public int PosY {get; set;}
}

Now you can create dictionary where key will be your string part name and value will be instance of Location class

Dictionary<string, Location> part = new Dictionary<string, Location>();

To store values in result,

  part.Add("part1", new Locataion(1, "part 1", 100, 200));
  part.Add("part2", new Locataion(2, "part 2", 300, 250));

To print value Name of part2, you can do

Console.WriteLine(part["part2"].Name);

Upvotes: 2

Related Questions