Home > Blockchain >  How can I match a specific existing object by a string property?
How can I match a specific existing object by a string property?

Time:12-21

I am trying to make a query system for objects, but I have been unable to figure out how to turn string from Console.ReadLine() to an objects name. Here is an example code snippet:

class Program
{
    Notes note = new Notes();
    note.notes = "note";

    Notes note2 = new Notes();
    note2.notes = "note2";

    Console.WriteLine("which note would you like?");
    string which = Console.ReadLine();
    if(which.ToUpper == ("NOTE" || "NOTE2")
    {
        Console.WriteLine(which   "\'s note is "   which.note);//this is where I need to find an object from a string
    }else
    {
        Console.WriteLine("There is no note called "   which);
    }
}
class Notes
{
    string notes;
}

For context, I intend to add a lot more objects into this and a large amount of if statements to find the right object will not be very practical

If I need to be more clear, please say so. Thanks for any help you can give.

CodePudding user response:

if (which.ToUpper() == "NOTE" || which.ToUpper() == "NOTE2")

CodePudding user response:

since there can be many notes, you can use list to search

Notes note = new Notes();
note.notes = "note";

Notes note2 = new Notes();
note2.notes = "note2";

var noteList = new List<Notes>();
noteList.Add(note);
noteList.Add(note2);

Notes foundNote = null
foreach(var note in noteList)
{
    if (note.notes.Equals(which, StringComparison.OrdinalIgnoreCase))
    {
        foundNote = note;
        break;
    }
}


if (foundNote != null)
    Console.WriteLine("the note is {0}", foundNote.Notes);
else
   Console.WriteLine("no notes");


CodePudding user response:

you have two choices either you can choose dictionary or use the reflection approach.

solution with dictionary.

Dictionary<string, Notes> dict = new Dictionary<string, Notes>();

Notes note = new Notes();
note.notes = "note";
dict["note"] = note;


Notes selectedNote = dict[which];
Console.WriteLine($"{which}'s note is {selectedNote.notes}");

solution with reflection.

FieldInfo field = typeof(Program).GetField(which, BindingFlags.NonPublic);
if (field != null)
{
    object selectedNote = field.GetValue(null);
    Console.WriteLine($"{which}'s note is {((Notes)selectedNote).notes}");
}
  • Related