簡體   English   中英

LINQ組列表 <object> 在baseclass屬性上

[英]LINQ group List<object> on baseclass attribute

我得到一個列表,在其中放置了超類的子類實例。

我班的代碼:

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

我希望能夠基於我的基類(即制造)中的屬性對這些實例進行分組。

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

就像是

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

任何建議表示贊賞:)

你對什么感興趣

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM