C
C#12mo ago
LeviCoding

Fast search an object in a list using his attribute

So I have a list of ships and each ship has a length width, mass and a name. We need to write a method that searches in this list the oobject using his name attribute. So only a string is given with the method. for example public Ship SearchShip(string shipName){}
3 Replies
LeviCoding
LeviCodingOP12mo ago
c#
public abstract class Schip
{
private double _lengte;
public double Lengte { get; set; }

private double _breedte;
public double Breedte { get; set;}

private double _tonnage;
public double Tonnage { get; set; }

private string _naam;
public string Naam { get; set; }

public Schip(double lengte, double breedte, double tonnage, string naam)
{
Lengte=lengte;
Breedte=breedte;
Tonnage=tonnage;
Naam=naam;
}
}
c#
public abstract class Schip
{
private double _lengte;
public double Lengte { get; set; }

private double _breedte;
public double Breedte { get; set;}

private double _tonnage;
public double Tonnage { get; set; }

private string _naam;
public string Naam { get; set; }

public Schip(double lengte, double breedte, double tonnage, string naam)
{
Lengte=lengte;
Breedte=breedte;
Tonnage=tonnage;
Naam=naam;
}
}
c#
public Ship SearchShip(List<Ship> ships, string shipName){}
c#
public Ship SearchShip(List<Ship> ships, string shipName){}
We can not use lambdas, cuz we only learn it later in our course.
joren
joren12mo ago
iterate over the ships and compare the Naam with the shipName
public static Schip SearchShip(List<Schip> ships, string shipName)
{
foreach (Schip ship in ships)
{
if (ship.Naam.Equals(shipName, StringComparison.OrdinalIgnoreCase))
return ship;
}
return null; // or throw an exception, whatever your assignment states
}
public static Schip SearchShip(List<Schip> ships, string shipName)
{
foreach (Schip ship in ships)
{
if (ship.Naam.Equals(shipName, StringComparison.OrdinalIgnoreCase))
return ship;
}
return null; // or throw an exception, whatever your assignment states
}
(unhide to see an example of an solution)
LeviCoding
LeviCodingOP12mo ago
Is the use of a dictionary not faster? and using the name of the object as a key
Want results from more Discord servers?
Add your server