简体   繁体   中英

How to convert IEnumerable<CustomType> to List, applying grouping logic, and convert back to IEnumerable<CustomType>?

I want to take a list of items from a table, apply grouping logic(grouping by assignment type, start and end time), and then convert back to starting type.

  IEnumerable<Assignment> assignments = UnitOfWork.AssignmentRepository.Get(filter: a => a.Start.CompareTo(start) >= 0
                    && a.End.CompareTo(end) <= 0,
                    orderBy: o => o.OrderBy(a => a.Start));

    List<Assignment> pre_alerts = new List<Assignment>();

 foreach (Assignment a in assignments)
            {
                foreach (AssignmentType t in assignmentTypes)
                {  // determine if the assignment's type has a minimum required
                    if (a.AssignmentTypeID == t.AssignmentTypeID && t.Minimum>0)
                    {

                        // get the minimum assignments requierd
                        int min_required = t.Minimum;

                        DateTime s = a.Start;
                        DateTime e = a.End;
                        AssignmentType type = a.AssignmentType;

                        IEnumerable<Assignment> minimum_assignments = UnitOfWork.AssignmentRepository.Get(filter: m => m.Start.CompareTo(s) >= 0 && m.End.CompareTo(e) <= 0 && m.AssignmentTypeID == a.AssignmentTypeID, orderBy: o => o.OrderBy(m => m.Start));

                        int min_actual = minimum_assignments.Count();

                        if (min_actual < min_required)
                        { 
                        // add a single alert for time range and assignment type
                           pre_alerts.Add(a);
                        }
                    }
                }
            }
 var alerts = pre_alerts.GroupBy(x => new Assignment{ x.AssignmentTypeID, x.Start, x.End }).Select(k => k);

how do I convert alerts to IEnumerable<Assignment> ?

When using Select you are already returning it as an IEnumerable. If you want it to be of your type then:

var alerts = pre_alerts.GroupBy(x => new Assignment{ x.AssignmentTypeID, x.Start, x.End }).Select(k => k.Key);

The result of a GroupBy is an IGrouping so by Selecting just k you are returning an IEnumerable<IGrouping<Assignment...>>

But it feels to me that if that is the case then there is no reason to use the GroupBy but just Select to create the assignments and then distinct

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