-3

I have a list of a class called DTOPriceLine that contains 10 properties that hold Quantity Breaks for pricing, they can all be null and that would be fine, but if at least one of them is not null, I have to validate it for skips.

for example if only QtyBreak1New and QtyBreak3New are not null, this means QtyBreak2New was skipped (null), another example is if only QtyBreak2New is not null, then QtyBreak1New was skipped, if QtyBreak1New is not null and QtyBreak2New is not null then all is fine.

The business rule is you cannot skip breaks, they have to be sequential. Is there a better way to do this?

        foreach(DTOPriceLine line in linesWithBreaksToValidate)
        {
            List<int> breakOrder = new List<int>();
            if (line.QtyBreak1New.HasValue)
                breakOrders.Add(1);
            if (line.QtyBreak2New.HasValue)
                breakOrders.Add(2);
            if (line.QtyBreak3New.HasValue)
                breakOrders.Add(3);
            if (line.QtyBreak4New.HasValue)
                breakOrders.Add(4);
            if (line.QtyBreak5New.HasValue)
                breakOrders.Add(5);
            if (line.QtyBreak6New.HasValue)
                breakOrders.Add(6);
            if (line.QtyBreak7New.HasValue)
                breakOrders.Add(7);
            if (line.QtyBreak8New.HasValue)
                breakOrders.Add(8);
            if (line.QtyBreak9New.HasValue)
                breakOrders.Add(9);
            if (line.QtyBreak10New.HasValue)
                breakOrders.Add(10);

            var skipped = breakOrder.Select((x, i) => new { V = x, Index = i+1 }).Where(p => p.Index != p.V).Any();
        }
Alex
  • 2,247
  • 1
  • 27
  • 37

1 Answers1

1

The index is available not only on Select, but also on Where:

Where(IEnumerable, Func<TSource,Int32,Boolean>)

Thus, your linq expression can be shortened to:

var skipped = breakOrder
                .Where((number, index) => number != index+1)
                .Any();
Lesiak
  • 22,088
  • 2
  • 41
  • 65