2

I'm trying to convert a list of ints (-100, -80, -60, -40, -20, 0) into a list of min max range pairs [-100, -80], [-80, -60], [-60,-40], [-40, -20], [-20, 0]

I have a C style forloop that does this but it's very inelegant. It relies on the exception to stop processing. There should be a way to use a LINQ or an IEnumerable query for this, right? I've been trying to think of a query that could satisfy this but I'm coming up with blanks.

var signalStrengthBuckets = new List<IMinMaxRange<int>>();
for (int i = 0; i < thresholdList.Count; i++)
{
    try
    {
        signalStrengthBuckets.Add(
        new MinMaxRange<int>(thresholdList[i], thresholdList[i + 1]));
    }
    catch (Exception e)
    {
        break;
    }
}
user2619824
  • 478
  • 1
  • 5
  • 20
  • 2
    "inelegant" or not ... I've seen LINQ do some HORRENDOUSLY inefficient things building IEnumerable sublists. Maybe the C style for loop is actually your best bet :) – paulsm4 Aug 13 '18 at 22:20
  • You're right, it is. Please close this! I think my title is better though. – user2619824 Aug 13 '18 at 22:20
  • 2
    Also, those LINQs are nasty lol. I'll just stick to the forloop version with slight modifications to remove the exception handling, much more readable. – user2619824 Aug 13 '18 at 22:27
  • 3
    If u change your condition thresholdList.Count -1, you can avoid the exception – Gauravsa Aug 13 '18 at 22:27
  • `var signalStrengthBuckets = thresholdList.Skip(1).Select((v, i) => new MinMaxRange(thresholdList[i], v)).ToList()` – Slai Aug 13 '18 at 22:31
  • Check out `MoreLinq`'s `PairWise` - https://github.com/morelinq/MoreLINQ/blob/master/MoreLinq/Pairwise.cs – mjwills Aug 13 '18 at 23:11

0 Answers0