Locate and update runtime created object - c#

Haven't found a duplicate answer to this yet, so here goes..
I need to create 'objects' (could be key:value pair, but I need to databind) during runtime from data I receive from a serial port.
For example I'll receive "012320.50". I am breaking this into an object/key for "0123" with a value of "20.50". I also need to databind a control to this. I can't know how many, or the 'name' of these sources until the data is streamed in. So i need to create them dynamically.
That said, I was planning on using a list of objects...but I hope there is a better solution. And I haven't figured out how to bind to these yet...?
Mock-example:
class myObject{
int Name{get;set;}
double Value{get;set}
}
Dictionary<int, myObject> dict = new Dictionary<int, myObject>();
when serial data is received I parse then create the object:
dict.Add(name, new myObject(Name=name, Value = value});
Now for my questions:
When the value comes through again for a source, how can I reference that and assign a new value? I was thinking of iterating through the Dictionary and if(Name == name) kinda stuff to change the value, but I'm thinking that's terrible and inefficient. Hopefully someone has a better way?
How can I databind a control to the same object? Not sure here at all...just starting with WPF. I understand how to databind...but to a dynamic object, not so much.

Related

How to create the ability to apply a generic data source class

This is maybe something I know how to do or have already done it in the past. For some reason I am drawing a blank on how to wrap my head around it. This is more for learning as well as trying to implement something in my app.
I am using a set of third party controls. These controls offer a lot of functionality which is great. However, I want to be able to create a custom object that handle the logic/properties for the datasource of this control.
For example, there is a spreadsheet like object that I am using. You supply the spreadsheet like object some data and it pulls in your data. The problem here is that you need to set the columns, their data types, and other formatting/events as well as some logic to spit the data back to the user.
List<CustomClassWithProperties> dataSource
The custom class has some properties that will be translated to the columns. Like ProductName, Price, SalesDepartment, DatePurchased etc. This can be done by supplying the spreadsheet the columns and their data types each time. I want to be able to create a helper class that you just supply a list, a visible column list, and an editable column list and the data will fill in without any other issues.
Using the above list, I would imagine something similar to this:
DataHelperClass dtHlpr = new DataHelperClass(List<CustomClassWithProperties> data, List<string> visibleColumns, List<string> editableColumns)
This data helper class will take the data input list as the spreadsheet data source. It would then take the visibleColumns list and use that to set the visible rows, same for editableColumns.
Where I am running into a mental block (long week) is when I want to be able to reuse this. Let's say I have a List that has completely different properties. I would want my constructor for the data helper to be able to handle any List I send to it. Looking at whatever code I can get to for the third party controls, it appears that their data source is of type object.
Could someone point me in the right direction? I am thinking it has to do with generics and some interface implementation. I just honestly cannot think of where to start.
You can make the class itself generic:
public class DataHelperClass<T>
{
public DataHelperClass(List<T> data, ...) { ... }
}
DataHelperClass<CustomClassWithProperties> dtHlpr = new DataHelperClass<CustomClassWithProperties>(List<CustomClassWithProperties> data, List<string> visibleColumns, List<string> editableColumns)
You'd then perform your reflection against typeof(T).
I'd also be tempted to use IEnumerable<T> rather than List<T> if possible, but that's a matter of preference, more or less.
This is similar to using a simple List<object>, except that it enforces that all objects in the list inherit from the same type (which might well be object), so you get some more type-checking than you otherwise would.
You mentioned interfaces, I don't see any reason here to include that (from what you've told us, at least), but you can certainly make a generic interface via the same syntax.

Is it OK to use dictionaries when I don't need to quickly access their values?

Normally, I use a dictionary like a list, but with a key of a different type. I like the ability to quickly access individual items in the dictionary without having to loop through it until I find the item with the right property (because the property I'm looking for is in the Key).
But there is another possible use of a dictionary. I could just use the Key to store property A and the Value to store property B without ever using the dictionary's special functionality. For example, I could store a list of persons just by storing the forename in the key and the family name in the value (let's assume, for the sake of simplicity, that there won't ever be two people with the same forename, because I just couldn't come up with an better example). I would only use that dictionary to loop through it in a foreach loop and add items to it (no removing, sorting or accessing individual items). There would actually be no difference to using a List<KeyValuePair<string, string>> from using a Dictionary<string, string> (at least not in the example that I gave - I know that I could e. g. store multiple items wiht the same key in the list).
So, to sum it up, what should I do when I don't need to use the special functionalities a dictionary provides and just use it to store something that has exactly two properties:
use a Dictionary<,>
use a List<KeyValuePair<,>
use a List<MyType> with MyType being a custom class that contains the two properties and a constructor.
Don't use dictionaries for that.
If you don't want to create a class for this purpose, use something like List<Tuple<T1,T2>>. But keep in mind a custom class will be both more readable and more flexible.
Here's the reason: it will be much more easy to read your code if you use proper data structures. Using a dictionary will only confuse the reader, and you'll have problems the day a duplicate key shows up.
If someone reads your code and sees a Dictionary being used, he will assume you really mean to use a map-like structure. Your code should be clear and your intent should be obvious when reading it.
If you're concerned with performance you should probably store the data in a List. A Dictionary has lots of internal overhead. Both memory as well as CPU.
If you're just concerned with readability, chose the data structure that best captures your intent. If you are storing key-value pairs (for example, custom fields in a bug tracker issue) then use a Dictionary. If you are just storing items without them having some kind of logical key, use a List.
It takes little work to create a custom class to use as an item in a List. Using a Dictionary just because it gives you a Key property for each item is a misuse of that data structure. It is easy to create a custom class that also has a Key property.
Use List<MyType> where MyType includes all the values.
The problem with the dictionary approach is that it's not flexible. If you later decide to add middle names, you'll need to redesign your whole data structure, rather than just adding another field to MyType.

Multiple options for keys in a dictionary?

Half the time I need to find a value based on string, their name, and the other half I need to find a value based on an int, their user ID.
Currently I have two dictionaries to solve this dilemma - one that uses a string as a key and one that uses an int as a key. I was wondering if there is a more efficient way to do this - a way to get a value based on int or string.
public static Dictionary<int, Player> nPlayers = new Dictionary<int, Player>();
public static Dictionary<string, Player> sPlayers = new Dictionary<string, Player>();
After scanning the other questions, someone mentioned using a dictionary of dictionaries. If anyone can elaborate on this (if it's the solution I'm looking for), that'd be grand
I don't know much about a tuple, but from what I understand it requires two keys, and what I am looking for takes one or the other.
Would Dictionary<object, Player> do the trick? I have no idea.
Please help me in my narrow-minded coding experience. ;_;
As per your comment when user logged in to system you adding them to a dictionary, here you have to add to both dictionaries.
I think you can do this in another way,
public static List<Player> nPlayers = new List<Player>();
That's only you need, add players when they logged in.
If you want to search by ID, Name or whatever you can query nPlayers and find the Player.
var playerByID = nPlayers.Where(p= p.ID==givenID).FirstOrDefault();
var playerByName = nPlayers.Where(p= p.Name==givenName).FirstOrDefault();
I don't think having a Dictionary<object,Player> is a better idea than having two distinct dictionaries. It will probably take the same amount of memory (since each Player reference will still be stored twice in the unified dictionary), will probably be less clear, and might (conceivably) cause problems with hashcode collisions since your key can be several different types.
I would just keep two dictionary, PlayersByName and PlayersByID, and use them when appropriate.
Do you want to know in the future the original data type that was put in the Dictionary? If not, you have two options:
Stringly typed! - Just use a string as the key and when adding to it, call .ToString() on the integers :)
Be objective - Use an object as the key, that way you can put anything you like inside it.
Based on the 2, I'd recommend the first as you still have some kind of type restrictions in there.
If you do want to know the original data type in the future - your implementation is fine :)
Your solution (2 dictionaries) is correct one. Dictionary can only be indexed by one stable key. As result you have to keep separate dictionaries to index by different keys.

Fastest data structure to check if a property within a list of objects matches

I've got a list which stores a number of objects. Each object has a property in the form of a variable.
I'd like to be able to check if any of the items in this list contain a certain property. Similar to the Dictionary's ContainsKey method. This data structure is to hold an extremely large amount of values, possibly even millions and I would thus like to use a data structure which can check the properties as fast as possible.
Would Dictionary be the fastest for this job, or are there faster data structures?
EDIT:
Here's a quick, small example of what I'd like to achieve:
Dictionary<string, Person> persons = new Dictionary<string, Person>(); //where string contains the Person's name
bool isPresent = persons.ContainsKey("Matt");
It sounds like you basically just need a HashSet<T> containing all the property values - assuming you really just want to know whether it's contained or not.
For example:
var allNames = new HashSet<string>(people.Select(person => person.Name));
It depends. If you can load the data into a dictionary once and then query it multiple times, then a dictionary is clearly the fastest possible data structure. If several items can have the same property value, you will have to create a Dictionary<TKey,List<TValue>> or to use a LINQ Lookup.
However, if you have to load the list each time you query it, then there is no benefit in using a dictionary. You can detect the right properties while loading the list or, if you are querying a database, then try to load just the required data by using an appropriate where clause.

Objective-C converting to C#: How can I use a .plist with multiple types in C# if Dictionary is strongly-typed?

The question is a bit complicated so I will try and explain. I have a custom .plist (XML Property List) file I created with Xcode. Within it is many different types of data: NSDictionary, NSArray, NSString, BOOL, etc.
Here's an example:
In my code I can quickly obtain an NSDictionary of this entire file without knowing an data types using the following code (this is ARC code by the way). The only data types that I DO know of is that all of the keys are strings, but the values can be anything I've shown above:
+ (NSDictionary *)configDictionary
{
collectorstemplateAppDelegate *appDelegate = (collectorstemplateAppDelegate*)
[[UIApplication sharedApplication] delegate];
NSString *path = [[NSBundle mainBundle]
pathForResource:appDelegate.currentPlist ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
return dict;
}
What I am trying to do is to accomplish the same thing on C#. I'd like to take these plists and move them to my Windows Phone phone apps, keeping the same structure. I realize that I will need to write some additional code to handle the XML behind the file, but you get the idea.... I want a Dictionary or HashTable or Collection of something similar to what I've done above, without knowing the types of the values.
Obviously in my case something like Dictionary<string, string> isn't going to work for me.
Any help would be great.
Answering my own question here but looking for validation....
Would Dictionary<string, object> work? Because I know the key is a string, I would just need to cast the value to the appropriate type, correct?
int appleID = (int) plistDict["appleid"];
If this is correct or incorrect, someone please let me know.
Hashtable is a non-generic version of Dictionary. In other words it doesn't require you to specify the types it deals with, and you can cash like you would in Objective-C.

Categories

Resources