Home > Software design >  Finding/Checking objects in a list based on Class
Finding/Checking objects in a list based on Class

Time:11-29

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"

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!

CodePudding user response:

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.");
}

CodePudding user response:

A compact solution using LINQ:

var filtered = nList.Where(n => n.Type != "Integer").ToList();

if (nList.Count == filtered.Count) {
    Console.WriteLine("There are no integers in the list.");
}

You also should not be modifying a collection you are iterating over.

  •  Tags:  
  • c#
  • Related