I got a List where I place instances of subclasses from a superclass.
Code for my classes:
public abstract class Vehicle : IComparable< Vehicle >, IComparable
{
public string Manufacture{get;set}
public Int16 VehicleID{get;set}
public DateTime ProductionDate{get;set}
public Vehicle(Int16 _ Vehicle ID,DateTime _ProductionDate)
{
this.AccidentID = _ AccidentID;
this.ProductionDate = _ProductionDate;
}
int IComparable.CompareTo(object other)
{
return CompareTo((Vehicle)other);
}
public int CompareTo(Vehicle other)
{
return this.ProductionDate.CompareTo(other.ProductionDate);
}
public Vehicle()
{}
}
public class Car : Vehicle
{
public Car ()
{
}
public Car (Int16 _VehicleID,DateTime _ProductionDate, Int16 _CarAttribute1, Int16 _CarAttribute2):base(_Vehicle ID,_ProductionDate)
{
this.AccidentID = _ AccidentID;
this.ProductionDate = _ProductionDate;
this.CarAttribute1 = _CarAttribute1
this.CarAttribute2 = _CarAttribute2
}
public Int16 CarAttribute1{ get; set;}
public Int16 CarAttribute2{ get; set;}
}
public class MotorCycle : Vehicle
{
public MotorCycle ()
{
}
public MotorCycle (Int16 _VehicleID,DateTime _ProductionDate, Int16 _MotorCycleAttribute1, Int16 _MotorCycleAttribute2):base(_Vehicle ID,_ProductionDate)
{
this.AccidentID = _ AccidentID;
this.ProductionDate = _ProductionDate;
this.MotorCycleAttribute1 = _MotorCycleAttribute1
this.MotorCycleAttribute2 = _MotorCycleAttribute2
}
public Int16 MotorCycleAttribute1{ get; set;}
public Int16 MotorCycleAttribute2{ get; set;}
}
I want to be able to group these instances based on an attribute in my base class, ie Manufacture.
public class Grouping<K, T> : ObservableCollection<T>
{
public K Key { get; private set; }
public Grouping(K key, IEnumerable<T> items)
{
Key = key;
foreach (var item in items)
this.Items.Add(item);
}
}
something like
var sorted = item in allVehicles //including cars and motorcycles
orderby item.Manufacture
group item by item.Manufacture into vehicleGroup
select new Grouping<string, object>(vehicleGroup.Key, vehicleGroup);
Any suggestions are appreciated :)
What are you interested for?
1. Get all from one type
Are you only interessted in getting eg Cars? Then add at the begin to your linq statement following condition:
.OfType<Car>()...
(Thanks to Stephen Kennedy, its more simple then "Where(one => one is Car).Cast()")
2. Get types grouped
Or do you want to get all types grouped? Then use
var list = allVehicles.GroupBy(t => t.GetType());
or
ILookup<Type, Vehicle> group = allVehicles.ToLookup(x => x.GetType());
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.