如何创建复杂的IEnumerable.GroupBy,其中keySelector是有条件的?

时间:2016-05-31 11:19:50

标签: c# linq

我一直用3个字段用简单的keySelector(type,classid,value)对数据项进行分组,但是现在我需要有条件keySelector来取决于类型的值。如果满足某些条件(取决于要分组的项目的类型和数量),它应该有效地将相同类型的不同值,classid有时组合成1组,具体取决于类型。

我在DataGrid中使用了类:

public class MaintenanceDataItem
{
    public MaintenanceDataItem(int classId, Type objectType, object value, IEnumerable<MmsData> rows)
    {
        ClassId = classId;
        TypeOfObject = objectType;
        Value = value;
        ObjectIds = new List<int>();
        foreach (var row in rows)
        {
            Count++;
            ObjectIds.Add(row.ObjectId);
            if (row is MmsObservation && (row as MmsObservation).Urgency > MaxUrgency)
                MaxUrgency = (row as MmsObservation).Urgency;
        }
    }

    public int ClassId { get; private set; }

    public Type TypeOfObject { get; private set; }

    public object Value { get; private set; }

    public int Count { get; private set; }

    public int MaxUrgency { get; private set; }

    public List<int> ObjectIds { get; private set; }
}

我有数据类,例如继承抽象类MmsData的MmsObservation。 DataGrid ItemsSource绑定调用方法:

private IEnumerable<object> GetSelectedObjectsMmsData()
{
       IEnumerable<MmsData> getMmsData;

       if (ShowOnlyFaults)
       {
           getMmsData = MaintenanceStore.GetMmsData(_selectedObjects.GetSelectedObjectItems(x => true)).Where(data => IsFault(data));
       }
       else
       {
            getMmsData = MaintenanceStore.GetMmsData(_selectedObjects.GetSelectedObjectItems(x => true));
       }
       var groups = getMmsData.GroupBy(
                   data => new { Type = data.GetType(), Id = data.MmsClassId, Value = data.Value}, (key, rows) => new MaintenanceDataItem(key.Id, key.Type, key.Value, rows));

       foreach (var item in groups)
       {
           yield return item;
       }
}

分组不简单的条件是:

if objectType!= MmsObservation and count&gt; 1,不同的值分组为&#34;&#34;

0 个答案:

没有答案