I'm new in C# and my question is, exist on C# arrays like PHP for example
$array = array("name" => array(), "Age" => array());
I want to know if is possible to make an array like that on C#
The closest you can get is a Dictionary<string, string[]>
This gives you the hashtable-type string lookup that returns an array. Note that you need to replace string[] with an array of the type that you want to store.
Lookups then work like this:
var dict = new Dictionary<string, string[]>() {
{ "name", new string[] { "Bob", "Sally" } },
{ "age", new string[] { "twenty four", "twenty three" } }
}
That being said, that's not the C# way of storing data. I'm going to go out on a limb and guess that you're storing a list of people. In C# you're much better off creating a class Person with attributes Name and Age, then populating and holding a list of the people. Example:
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
var bob = new Person { Name = "Bob", Age = 24 };
var sally = new Person { Name = "Bob", Age = 23 };
var people = new List<Person>() { bob, sally };
You could create your own class
public class People{
public List<string> Names { get; set; }
public List<int> Ages { get; set; }
}
this will allow you to have a class with a list of names and a list of ages. Though I don't think this is really want you want to do or perhaps a better response is: There is a better way to do what you want to do which looks like you want to loop through some names and their RELATED ages.. in which case, you would be better off with something like this:
public class Person{
public int Age { get; set; }
public string Name { get; set; }
}
List<Person> people =new List<Person>{
new Person{Age=20,Name="Bob"},
new Person{Age=25,Name="Sue"},
};
Now you have OBJECTS to work with that hold information in a more relational manner. This will completely avoid having to associate by index.
Related
I have an array filled with the names if some classes in my program .
string[] arr= new string[] {"company", "pokemon", "parents"}
is it possible to create an instance of a class like this:
list.Add(new class( arr[0] { "sdfs", "sfds", 123} ))
Maybe you are looking for object initialisers?
Assuming you have a class Pokemon:
class Pokemon {
public string Name { get; set; }
public string Type { get; set; }
public int Age { get; set; }
}
and a List<Pokemon> called list, you can do this:
list.Add(new Pokemon { Name = "sdfs", Type = "sfds", Age = 123 });
If I want to store data as Document in Clouchbase.lite is has to be in the form of Dictionary like this:
var properties = new Dictionary<string, object>()
{
{"type", "list"},
{"title", "title"},
{"created_at", DateTime.UtcNow.ToString ("o")},
{"owner", "profile:" + userId},
{"members", new List<string>()}
};
var rev = document.PutProperties(properties);
How can I automatically create such a Dictionary from any C# object?
If I understand the couchbase.lite documentation this process does not to be recursive, just on the first level of my object fields and properties.
How can I recreate my objects from such a dictionary?
Ok, this not a full answer to my question, but it solves the problem for now. I came to the solution of putting the whole object into the Dictionary that is handed to Couchbase.Lite:
var c = new TestClass() {TestString = "SimpleStringfield", TestDate = DateTime.Today,TestStringProperty = "TestStringPropertyContent",
TestStringList = new List<string>(new string[] { "item1","item2","item3"})};
var manager = Manager.SharedInstance;
var db = manager.GetDatabase("test_database");
if (db == null)
{
System.Diagnostics.Debug.WriteLine("--------------------------Could not open Database");
}
var doc = db.CreateDocument();
var properties = new Dictionary<string,Object>() { {"type","day"}, {"day",c} };
var rev = doc.PutProperties(properties);
var docread = db.GetDocument(doc.Id);
JObject testobject = (JObject)docread.GetProperty("day");
var o = testobject.ToObject<TestClass>();
}
At the end o contains the same values as c.
I want to point out the warning that Jim Borden gave me to this approach:
I will always assert that the "right way" is the way that works. The
fact that the library uses JSON .NET internally is an implementation
detail, though. If that were to change for some reason then this way
would break. I also have a feeling that if the class were more complex
than your example than it would break as well. We are currently
designing a cross platform specification to do just what you want to
do (save classes directly to the database without converting to a
dictionary first). This will be a slow process though because there is
a lot of thought that needs to go into it (not just for C#, but for
Java and Objective-C as well). For example, how to serialize a class
that has a property which references back to it, etc. I know JSON .NET
already does this, but I don't want to start exposing JSON .NET into
the public API because eventually it should be switchable (in case
JSON .NET does not work for whatever reason on a platform).
I know you are talking about automatic, but I needed the individual fields of my class to be exposed so I can index them and run mapped queries. So I specified all my query-able objects to follow this interface:
public interface IEntity
{
string Id { get; set; }
IDictionary<string, object> ToDictionary();
void PopulateFrom(IDictionary<string, object> prop);
}
And typically implemented as follows:
public class Club : IEntity
{
public string Id { get; set; }
public string Name { get; set; }
public string Country { get; set; }
public string Place { get; set; }
public long ClubId { get; set; }
public string Access { get; set; } = "read";
public List<ClubMember> Members { get; set; }
public void PopulateFrom(IDictionary<string, object> prop)
{
Name = prop.GetOrDefault<string>("name");
Country = prop.GetOrDefault<string>("country");
Place = prop.GetOrDefault<string>("place");
ClubId = prop.GetOrDefault<long>("club_id");
Access = prop.GetOrDefault<string>("access");
Members = ParseMembers(prop["members"]);
}
public IDictionary<string, object> ToDictionary()
{
return new Dictionary<string, object>
{
{ "club_id", ClubId },
{ "name", Name },
{ "country", Country },
{ "place", Place },
{ "access", Access },
{ "members", Members}
};
}
}
I am fairly new to programming and am trying to wrap my head around classes. I have created a class like the following:
public class HistoricalEvents
{
public DateTime historicDate { get; set; }
public string historicEvent { get; set; }
}
I want to be able to go into a MySQL database, pull multiple events, and then display those events onto the screen. How do you create multiple HistoricalEvents from MySQL and then iterate through them to display them onto a screen?
First, you need a class representing a single event, preferably named in the singular (eg HistoricalEvent instead of HistoricalEvents).
Then you can create a List<HistoricalEvent> like so:
public class HistoricalEvent
{
public DateTime historicDate { get; set; }
public decimal historicEvent { get; set; }
}
List<HistoricalEvent> historicalEvents = new List<HistoricalEvent>();
historicalEvents.Add(new HistoricalEvent());
// ... etc etc ...
Once you have your list, you can iterate it like so:
foreach (HistoricalEvent historicalEvent in historicalEvents)
{
// "historicalEvent" contains the current HistoricalEvent :)
}
Creating objects from a MySQL database is a lot more involved. If you want to jump in, try this tutorial (provided by Microsoft), and perhaps look into linq to objects, but I would suggest becoming more familiar with C# first :)
Edit:
That sounds a bit terse, so here's a similar example:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>();
people.Add(new Person()
{
Name = "Dave",
Age = 43
});
people.Add(new Person()
{
Name = "Wendy",
Age = 39
});
foreach (Person person in People)
{
Console.WriteLine(person.Name) // "Dave", then "Wendy"
}
This uses the Connector/Net ADO.Net provider:
var list = new List<HistoricalEvent>();
using (var cn = new MySqlConnection())
{
cn.Open();
var sql = "SELECT Date, Event FROM HistoricalEvents";
using(var cm = new MySqlCommand(sql, cn))
using(var dr = cm.ExecuteReader())
{
while (dr.Read)
list.Add(new HistoricalEvent
{
historicDate = dr.GetDate(0),
historicEvent= dr.GetString(1)
});
}
}
foreach (var item in list)
Console.WriteLine("{0}: {1}",item.historicDate,item.historicEvent);
I am new to C# but i have a background in PHP. Working some basic stuff in C# i came across some odd thing for me. I want to create an array of arrays in C# with string keys that hold another array of string keys. If I had to do this in PHP it whould look like this:
$workers = array("John" => array("salary" => 1000, "bonus" => 200),
"Michal" => array("salary" => 1500, "bonus" => 0)
);
Digging into C# I found some answers like hashtable or dictionary, but it made me more confused.
C# is not like PHP in that it is not loose so you need to declare exactly what the array (hashtable if you want string keys) can hold. Meaning if you wish to have an array of arrays, then the parent array needs to be told that it holds arrays and cannot hold anything else.
This has basicly been answered here:
How to initialize a dictionary containing lists of dictionaries?
Arrays in .NET doesn't have key-value pairs, so you would need to use a different collection for that, like a dictionary.
The closest to your PHP code would be a dictionary of dictionaries, however a dictionary of custom classes work be more in line with how data is handled in C#.
The class:
public class Worker {
public int Salary { get; set; }
public int Bonus { get; set; }
}
The dictionary:
Dictionary<string, Worker> workers = new Dictionary<string, Worker>();
workers.Add("John", new Worker{ Salary = 1000, Bonus = 200 });
workers.Add("Michal", new Worker{ Salary = 1500, Bonus = 0 });
This allows you to locate a worker by name, and then access the properties. Example:
string name = "John";
Worker w = workers[name];
int salary = w.Salary;
int bonus = w.Bonus;
Create a class for your object Worker:
public class Worker
{
public string Name { get; set; }
public double Salary { get; set; }
public int Bonus { get; set; }
public Worker(string name, double salary, int bonus)
{
this.Name = name;
this.Salary = salary;
this.Bonus = bonus;
}
}
Then create a List of workers:
List<Worker> workers = new List<Worker>() {
new Worker("John", 1000, 200),
new Worker("Michal", 1500, 0)
};
What you can do in c# is something like this :
public class Employee
{
public string Name { get; set; }
public double Salary { get; set; }
public int Bonus { get; set; }
public Employee(string name, double salary, int bonus)
{
this.Name = name;
this.Bonus = bonus;
this.Salary = salary;
}
}
And create dictionary :
Dictionary<string, Employee> emps = new Dictionary<string, Employee>();
emps.Add("Michal", new Employee("Michal", 1500, 0));
emps.Add("John", new Employee("John", 1000, 200));
Or sometimes you may wish to use dynamic and anonymous type for our employees rather then strong type (such as Employee) :
var John = new { Salary = 1000, Bonus = 200 };
var Michal = new { Salary = 1500, Bonus = 0 };
var dict = new Dictionary<string, dynamic>()
{
{"John", John},
{"Michal", Michal},
};
Console.WriteLine(dict["John"].Bonus);
output : 200
I have this model:
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
public List<Color> Colors { get; set; }
}
public class Color
{
public int ColorId { get; set; }
public string Name { get; set; }
}
and asp.net MVC's return Json(...) gives me this:
[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":29,"Colors":[{"ColorId":2,"Name":"Blue"}]}]
when I try to return a type of: List<Person>
but I want something like this (if possible):
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},{"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
MY QUESTION(S):
How can I make C# (asp.net mvc) return JSON with a better format of something like: (note: ignore the data, my main point is for it to return with "People" as the main collection.. how should I do this? JSON.net?)
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
OR how can I make KNOCKOUT.JS MAPPING PLUGIN work with this type of JSON format? (for those who know knockout)
[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":29,"Colors":[{"ColorId":2,"Name":"Blue"}]}]
UPDATE (extra clarification/info):
this is my data, and I want to return a List
private List<Person> _people = new List<Person>
{
new Person
{
Name = "JC",
Age = 24,
Colors = new List<Color>
{
Red,
Blue,
}
},
new Person
{
Name = "Albert",
Age = 29,
Colors = new List<Color>
{
Blue
}
}
};
in a JSON format similar to this:
{"People":[{"Name":"JC","Age":24,"Colors":[{"ColorId":1,"Name":"Red"},{"ColorId":2,"Name":"Blue"}]},
{"Name":"Albert","Age":83,"Colors":[{"ColorId":2,"Name":"Blue"}]}]}
i'm just wondering if that is possible, or if not, then how can I make the knockout.js mapping plugin adapt to MVC's way of returning json?
You need a container since you do not want to return an array but an object with a People variable.
Something like this (using dynamic):
var jsonData = new
{
People = _people
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Update
JSON is really simple format. Let's skip everything that you don't need to now.
Objects: Objects in json start and end with {}. Anything in them corresponds to properties in C#.
Arrays: Returning a IEnumerable will return an array. An array can contain other arrays, objects or simple fields.
The code above is using a dynamic object in C# and can be translated into a class looking like this:
public class MyCustomClass
{
public IEnumerable<Person> People {get;set;}
}
Hence it's an object returning an array resulting in:
{ People: [] }
Where the {} corresponds to MyCustomClass.
you can return things, in for example, this way:
var jsonData = new
{
Name = qry.Name,
Age = qry.Age,
Colors = (
from c in qry
select new
{
ColorID = c.ColorID,
Name = c.Name
}).ToArray()
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
Maybe something like that :)