I'm trying to find a struct I created earlier that has a specific value. Once I found it, I want to set variables on that struct. I don't know how to do this. Is there a better way of doing this? Maybe classes? Or should structs work?
For example, my struct:
public struct MyTest
{
public string device;
public string status;
public string revision;
public string number;
public string ledmo;
}
My Test Code:
MyTest thisTest=new MyTest();
thisTest.device=blah;
thisTest.number=blah2;
MyTest thisTest2=new MyTest();
thisTest2.device=blah5;
thisTest2.number=blah6;
//Another Part in my code.
//Need to find the MyTest Structure that 'device' variable = the string 'blah'
var Foundit=MyTest.find(device==blah);
Foundit.revision=blah9999;
You can use lists and Linq for that.
To be able to find instances of an object created earlier, these instances need to be saved somewhere.
One solution would be to put them into a list and later search that list:
Now you can search using LINQ:
Please note:
This only works when you use classes instead of structs as Binary Worrier points out in his comment.
In this case a class would work better because of the dynamic string size and the fact that there are so many strings.
With your test code, you should be storing a
List<MyTest>
somewhere in that class and addingthisTest
andthisTest2
to the list. You can later retrieve specific values (or all the values of a certaindevice
) with the FindAll or similar methods.I'd use a class, because Mutable structs are evil
Basically, because every
struct
is copied, even if you do find the right struct, you'll only ever change one copy. Lets sayMyTest.find
finds thisTest2 what happens is thisTo do this with a class you'll need to keep every instance of the class you create in a list or other data structure, so you know you can look it up.
If you do this you also need to tell the list when you're finished with each object, otherwise they'll hang around forever and never get garbage collected.
Before I go any further, are you sure this is the best way to solve this problem?
Anyway, say your class is
MyData
, you can put a static factory method on this calledCreate
, which will put each new MyData object into a list.Everywhere you use a MyData you'll need to
Delete
it when you're finished with it.Your code becomes
Changing FoundIt now also changes
thisTest
P.S.: It's important that nothing outside
MyData
cannew
an instance ofMyData
. If it could, then there would be an instance ofMyData
that you couldn't find in AllInstances. Declaring the constructor private means a compiler error will be generated if code outside MyData tries something likevar someData = new MyData