Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Finding/Checking objects in a list based on Class

This is a simplified version of what I am working on

Let’s say I have a list of objects with a pre-defined "Numbers" class

List<Numbers> nList = new List<Numbers>();

And let’s say that I have objects with pre-defined classes "Integer" and "Double"

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Integer int1 = new Integer(1);
Integer int2 = new Integer(2);
Double double1 = new Double(3.0);
Double double2 = new Double(4.0);

And I add them to the list, nList.

nList.Add(int1);
nList.Add(int2);
nList.Add(double1);
nList.Add(double2);

What I am working on is that, if the list contains an integer object, it removes that integer. If the list does not contain an integer object, it just prints a message saying that there is no integer object

My code goes something like

foreach (Numbers n in nList)
{
    if (n.Type == "Integer")
    {
        nList.Remove(n);
        break;
    }
    else
    {
        Console.WriteLine("There are no integers in the list.");
        break;
    }
}

My current code only checks 1 object at a time instead of all the objects before removing or displaying the message.

For example, if the first object has a "Double" class, the programme would stop immediately even though there are "Integer" objects behind it.

I accept any and all suggestions. Thanks!

>Solution :

bool hasInteger = false;
foreach (Numbers n in nList) {
    if (n.Type == "Integer") {
        nList.Remove(n);
        hasInteger = true;
    }
}
if (!hasInteger) {
    Console.WriteLine("There are no integers in the list.");
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading