简体   繁体   中英

c# search collection by field in base class

Given is a base class and some derived classes:

class baseVehicle
{
    public int Id { get; set; }
    public string vName { get; set; }
    public int maxSpeed { get; set; }
}
class truck : baseVehicle
{
    public int loadTons { get; set; }
}
class cabrio : baseVehicle
{
    public bool softTop { get; set; }
}
class suv : baseVehicle
{
    public int NoOfSeats { get; set; }
}

and all these vehicle objects are created and inserted into a collection:

public ObservableCollection<object> vehicles = new ObservableCollection<object>vehicles();

What is the most efficient way to find the vehicle with vName = "Alfa Romeo Giulietta" or with Id = 43?

You should create collection of baseVehicle ( baseVehicle is base class for others and you can add every object which has type of baseVehicle or type derived from baseVehicle ), not collection of object (you can use collection of object but you should cast elements to correct type):

public ObservableCollection<baseVehicle> vehicles = new ObservableCollection<baseVehicle>vehicles();

TO GET ONE ELEMENT:

You can use FirstOrDefault() - you can use First() but you should be sure that element exists in collection (with condition in lambda):

var vehicle = vehicles.FirstOrDefault(i => i.Id == 43);
if (vehicle != null)
{
    //some code
}

You can combine conditions using OR :

var vehicle = vehicles.FirstOrDefault(i => i.Id == 43 || i.vName == "some name");

Also, you can use AND :

var vehicle = vehicles.FirstOrDefault(i => i.Id == 43 && i.vName == "some name");

TO GET SEVERAL ELEMENTS:

Use Where() ;

var someVehicles = vehicles.Where(i => i.Contains("Alfa"));
//or
var someVehicles = vehicles.Where(i => i.Id == 2 || i.vName == "Some name);

如注释中所建议,使用ObservableCollection<baseVehicle>并对其进行过滤:

collection.where(x=>x.Id == 43 || x.vName == "Alfa Romeo Giulietta").FirstOrDefault();

将您的集合更改为ObservableCollection<baseVehicle>或者可以像这样ObservableCollection<baseVehicle>

vehicles.Cast<baseVehicle>().FirstOrDefault(i => i.Id == 43 || i.vName == "Name...");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM