LINQ组列表<;对象>;基于基类属性

本文关键字:属性 基类 于基类 gt 列表 lt 对象 LINQ | 更新日期: 2023-09-27 18:27:29

我得到了一个List,在其中我放置了超类中子类的实例。

我的课程代码:

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;}
}

我希望能够根据基类(即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);
    }
}
  • 更多信息,请访问:http://motzcod.es/post/94643411707/enhancing-xamarin-forms-listview-with-grouping-headers#sthash.kWyEfaqU.dpuf

类似的东西

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);

欢迎提出任何建议:)

LINQ组列表<;对象>;基于基类属性

您对什么感兴趣?

1.从一个类型中获取所有

你只是在买汽车方面受到了干扰吗?然后在linq语句的开头添加以下条件:

.OfType<Car>()...

(感谢Stephen Kennedy,它比"Where(one=>one is Car).Cast()"更简单)

2.获取分组的类型

还是要将所有类型分组?然后使用

var list = allVehicles.GroupBy(t => t.GetType());

ILookup<Type, Vehicle> group = allVehicles.ToLookup(x => x.GetType());