I need to create a property tha will hold to ints for example
int age and int numbers so.. something like This data is comming from a function in another class that returns a DataSet, in the data set there will be those two items like:
Age number
24 1
29 6
32 2
27 1
19 3
So like I said, at the end I would like to have a property that contains this data and can reference at any time from different classes
so I am not sure what to use to hold that data, but it would be something like
public <int, int> personData
{
get
{
return _personData;
}
set
{
_personData = value;
}
}
so I do not know what to use for _personData and for . And how can I access the values of such solution
I would appreciate your help
Looks like a Dictionary<int, int> will do it for you.
Dictionary<int, int> _personalData = new Dictionary<int, int>{ {24, 1}, {29, 6}, ..};
and to access values, you can do
int result = _personalData[24]; // should return 1
public class PersonData
{
public int Age{get;set;}
public int Number {get;set;}
}
You can then create List<PersonData>
And you can access each property like so:
PersonData personData = new PersonData();
personData.Age=12;
personData.Number=10;
You can create a list of PersonData and add items doing this:
List<PersonData> listPersondata = new List<PersonData>();
listPersondata.Add(new PersonData(){Age=12,Number=13});
You can bind this List to any control like a gridview, listbox, etc.
Related
Instead of doing my old non OOP way I am trying to do what people claim is best. I need to store about 9 different Int arrays of differing lengths. I also need to associate them with a String Name "this is called etc.." I was thinking it would make sense to store that all into a class object so I can cleanly iterate through them later on without looking to two different places using the same for loop iterator.
Example:
public class Thing
{
public List<int> SDNA {get; set;}
public string Name {get; set;}
}
List<Thing> things = new List<Thing>
{
new Thing { SDNA = {2,4,5,7,9,11},Name = "First Thing"}
}
I get a null ref exception (I am assuming its cause of the list within a class somehow) I tried creating a list this way to clear the null ref but it had some other errors.
List<Thing> things = new List<Thing>();
things.Add(new Thing() {SDNA = {2,4,5,7,9,11},Name = "The first things name"});
Errors of invalid token etc. Should I just do it with two different stored arrays, one for names and a jagged array for the Ints and then reference them each? That feels ugly to me. Why can't I store them all into one thing?
Thanks!
In the simplest case if you want just to have name to value (array) association, you can try using a simple Dictionary, e.g.
private Dictionary<string, List<int>> things = new Dictionary<string, List<int>>() {
{"First thing", new List<int>() {2, 4, 5, 7, 9, 11}},
};
then you can use it
// Add new thing
things.Add("Some other thing", new List<int>() {1, 2, 3, 4, 5});
// Try get thing
if (things.TryGetValue("First thing", out var list)) {
// "First thing" exists, list is corresponding value
}
else {
// "First thing" doesn't found
}
// Remove "Some other thing"
things.Remove("Some other thing");
// Iterate over all {Key, Value} pairs (let's print them):
foreach (var pair in things)
Console.WriteLine($"{pair.Key} :: [{string.Join(", ", pair.Value)}]");
However, if Thing is not just SDNA + Name combination (more properties, methods are expected) I suggest
private Dictionary<string, Thing> things
declaration
apologies if I'm doing something wrong, this is my first post.
I'm currently working with C# and want to save a bunch of data out to a JSON file and load it back, but I'm having trouble figuring out how to get it in the following format.
// Primary ID
001
{
// Secondary ID
01
{
// Tertiary ID
01
{
string: "this is some information.",
int: 9371
}
}
// Secondary ID
02
{
// Tertiary ID
01
{
string: "blah blah blah.",
int: 2241
}
}
}
I'd essentially like to be able to call up information with a particular set of IDs for example 001-02-01 which would return a string ("blah blah blah.") and an int (2241).
The reason I want to go about it like this instead of just having one longer ID is so that when the JSON file becomes very large, I'm hoping to be able to speed up the search for information by passing each ID in turn.
If that makes no sense and it would be equally as fast to just pass in one longer ID and not be bothered by this whole nested ID segments concept then please let me know!
If, however what I'm thinking is correct and it would help the speed of finding particular data by structuring it out like this, how would I go about doing that? With nested C# classes in arrays?
The most simple way and efficient way would be to have all data as same type. Currently, you seem to go for each object is of type of the given id:
{
"01":{},
"02" :{}
}
this will not go too well if trying to use a serializable class.
I would recommend the following:
{
"items" : [
{"id":"01" }, { "id":"02" },...
]
}
Then you can serialize/deserialize easily with
[Serializable]
public class Item
{
public string id = null;
}
[Serializable]
public class RootObject
{
public List<Item> items = null;
}
and then in Unity:
void Start(){
string str = GetJson(); // However you get it
RootObject ro = JsonUtility.FromJson<RootObject>(str);
}
if you want to speed up the fetching and your collection is large, convert to dictionary.
Dictionary<string, Item> dict = null;
void Start(){
string str = GetJson(); // However you get it
RootObject ro = JsonUtility.FromJson<RootObject>(str);
this.dict = new Dictionary<string,Item>();
foreach(Item item in ro.items){
Item temp = temp;
this.dict.Add(item.Id, temp);
}
ro = null;
}
Now you can access real fast.
Item GetItem(string id)
{
if(string.IsNullOrEmpty(id) == true){ return null; }
Item item = null;
this.dict.TryGetValue(id, out item);
return item;
}
If you end up storing millions of records in your file and want to start doing something more performant it would be easier to switch to a decent document database like MongoDB rather than trying to reinvent the wheel.
Worry about writing good standard code before worrying about performance problems that don't yet exist.
The following example is not in your language of choice but it does explain that JSON and arrays of 1,000,000 objects can be searched very quickly:
const getIncidentId = () => {
let id = Math.random().toString(36).substr(2, 6).toUpperCase().replace("O", "0")
return `${id.slice(0, 3)}-${id.slice(3)}`
}
console.log("Building array of 1,000,000 objects")
const littleData = Array.from({ length: 1000000 }, (v, k) => k + 1).map(x => ({ cells: { Number: x, Id: getIncidentId() } }))
console.log("Getting list of random Ids for array members [49, 60, 70000, 700000, 999999]")
const randomIds = ([49, 60, 70000, 700000, 999999]).map(i => littleData[i].cells.Id)
console.log(randomIds)
console.log("Finding each array item that contains a nested Id property in the randomIds list.")
const foundItems = littleData.filter(i => randomIds.includes(i.cells.Id))
console.log(foundItems)
I have a set of objects (say they are all different kinds of animals --- Bear, Bear, Lion, Tiger, Bear)
What is the best way to maintain a count for each animal?
I tried to use Dictionary but the "int" is of course read-only.
Ideally, I want something like animal["Bear"] = 2, animal["Lion"] = 1, animal["Tiger"] = 1 etc.
I tried to use Dictionary but the int is of course read-only.
int being a value type shouldn't stop you: you just need to treat it the way you treat immutable objects when you use them as dictionary values that need to change, i.e. by reassigning them.
Here is an example of how to increment a count inside a dictionary:
var counts = new Dictionary<Animal,int>();
Animal someAnimal = ... // Get some animal
int currentCount;
if (counts.TryGetValue(someAnimal, out currentCount)) {
counts[someAnimal] = currentCount+1;
} else {
counts.Add(someAnimal, 1);
}
You can try something like this
string[] animals = new string[] { "Bear", "Bear", "Lion", "Tiger", "Bear" };
var groups = animals.GroupBy(v => v);
foreach(var group in groups)
Console.WriteLine("[{0}] = {1}", group.Key, group.Count());
You can also make a Collection or List of Animals and get the count by its value type. Since it is not clear how your class looks like I have given example with the string.
Im working on a project in unity, im using a dictionary to store player information and then assigning a userID int to the players which is what im attempting to make the index position of the players information in the dictionary, but i think im trying to use this system completely wrong. Currently i have this code:
public class Players : IComparable<Players> {
public int userID;
public string userName;
public int userHealth;
public GameObject userPlayer;
public Players(int newID,string Name,int Health,GameObject player){
userID = newID;
userName = Name;
userHealth = Health;
userPlayer = player;
}
public int CompareTo(Players other){
if(other == null){
return 1;
}
return userID - other.userID;
}
}
to create the Dictionary i use
private Dictionary<NetworkPlayer, Players> playerList = new Dictionary<NetworkPlayer,Players>();
to add to it i use
playerList.Add(player,new Players(playerList.Count,"Test", 100, playerObj));
I was hoping to use the playerList.Count part as a method of indexing it and then sorting it by this index to get the player i wanted back... is there a way of doing this correctly? This is my first time attempting to use dictionarys in c# and im finding it hard to understand how they work, if someone could help lead me to a working method of doing this. All i need to be able to do is to return data based off its index OR using the NetworkPlayer class.
If anyone could help lead me to a working method of doing this id be grateful, Thanks.
A standard dictionary's items are not sorted in this way. Normally, if you want to pull out the player by a specific ID, it would be better to make that the key in the dictionary, ie:
private Dictionary<int, Players> playersByID = new Dictionary<int, Players>();
private Dictionary<NetworkPlayer, Players> playersByNetwork = new Dictionary<NetworkPlayer, Players>();
Note that you could store two dictionaries, one for each form of lookup:
You could then store:
int id = nextID; // Using ID counter...
var newPlayer = new Players(id, "Test", 100, playerObj);
playersById.Add(id, newPlayer);
playersByNetwork.Add(player, newPlayer);
And fetch via:
var player = playersById[120];
Or via:
var player = playersByNetwork[netPlayer];
On a side note: I didn't use the Count as an ID, since that will fail if you ever remove players... If that is something you will never do in your system, you could go back to using the Count property for your next id.
You can also index the dictionary values by yourself enveloping the key-value pair you are interested into a KeyValuePair and associating it with an int like so:
Dictionary<int, KeyValuePair<string, int>> indexedDictionary = new Dictionary<int, KeyValuePair<string, int>>
{
{0, new KeyValuePair<string, int>("my entry", 13) },
{1, new KeyValuePair<string, int>("whatever", 5) },
{............}
};
I just wanna ask what best way to work around a Two-Dimensional Array (2 Columns) which would store: CandidateName and their respective VoteCount.
What I want exactly to do is to, accept an input from the user say: VOTE John 10 wherein John is the name of the candidate and 10 is the votes that he wanna give him. So I need to store {John, 10} into my array. However, after this my program would once again ask the user for votes so if I enter VOTE Doe 15, the entry {Doe, 15} would then be added to the array. If the user enters VOTE John 2, my array needs to be updated and thus the new value would be {John, 12}.
Currently I use two arraylists: CandidateName and VoteCount and I just rely on their index for pairing. However, this isn't really reliable so I'm trying to find another way on how to solve this. However, I'm not really a big fan of multi-dimensional arrays.
Can someone please point me out to a good way on how to achieve this?
public class VoteManager
{
public Dictionary<string, int> Votes { get; private set; }
public VoteManager
{
Votes = new Dctionary<string, int>();
}
public void AddVotes(string name, int voteCount)
{
int oldCount;
if (!Votes.TryGetValue(name, out oldCount))
oldCount = 0;
Votes[name] = oldCount + voteCount;
}
You should use an Associative Array. In the case of C#, such a collection is the Dictionary.
var votes = new Dictionary<string, int>();
votes["John"] = 10;
votes["Bob"] = 20;
votes["John"] = 15; // replaces earlier setting
If you want to add to the exisiting vote, you will need to check if there is an existing value:
private Dictionary<string, int> votesByPeep; // initialized in constructor
private void AddVotes(string peep, int votes)
{
if (this.votesByPeep.ContainsKey(peep)
{
this.votesByPeep[peep] += votes;
}
else
{
this.votesByPeep[peep] = votes;
}
}
Why don't you define a struct/class with two properties, Name and VoteCount. Then you only need one array.
EDIT:
I suggested this because there may be additional operations or properties you want to add to Candidates. If all you need is an association between these two values, a dictionary is the correct solution.
It sounds like a much better solution here is to use a Dictionary<TKey, TValue>. A dictionary / hashtable is ideal for a scenario where you're pairing a value (vote count) with a given key (user name). It makes for very easy update and lookup scenarios
class Container {
private Dictionary<string, int> m_voteMap = new Dictionary<string, int>();
public void SetVote(string user, int votes) {
m_voteMap[user] = votes;
}
public int GetVotes(string user) {
int votes;
if (!m_voteMap.TryGetValue(user, out votes)) {
votes = 0;
}
return votes;
}
}
You can use a dictionary from strings (names) to int (votes), this will give you the {name, votes} pair and a nice quick lookup
Create a class called CandidateVotes, and store that in a List<CandidateVotes> collection.
public class CandidateVotes
{
public string Name {get; set;}
public int Votes {get; set;}
}
Dictionary<string, int> is your friend
This sounds like a good candidate for a Dictionary<T,U>. In this case, Dictionary<string,int>, with the key being the candidate, and the value being the vote count.
// Create dictionary as:
Dictionary<string, int> votes = new Dictionary<string, int>();
You could then make some routines like the following:
void AddVotes(string candidate, int numberOfVotes)
{
if (this.votes.Contains(candidate))
{
// Update the "10 to 12" in your scenario
int current = this.votes[candidate];
current += numberOfVotes;
this.votes[candidate] = current;
}
else
this.votes[candidate] = numberOfVotes; // First time a candidate is used...
}
When you want to list out the votes per candidate, you can do something like:
foreach(var pair in this.votes)
{
Console.WriteLine("Candidate {0} has {1} votes.", pair.Key, pair.Value);
}