Finding Consecutive Items in List using Linq

后端 未结 4 1425
借酒劲吻你
借酒劲吻你 2020-12-18 04:44

Say I have the following array of integers:

int[] numbers = { 1, 6, 4, 10, 9, 12, 15, 17, 8, 3, 20, 21, 2, 23, 25, 27, 5, 67,33, 13, 8, 12, 41, 5 };
<         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-18 05:22

    Why don't you try this extension method?

    public static IEnumerable> Consecutives(this IEnumerable numbers, int ranges, Func predicate)
    {
        IEnumerable ordered = numbers.OrderBy(a => a).Where(predicate);
        decimal n = Decimal.Divide(ordered.Count(), ranges);
        decimal max = Math.Ceiling(n); // or Math.Floor(n) if you want
        return from i in Enumerable.Range(0, (int)max)
               select ordered.Skip(i * ranges).Take(ranges);
    }
    

    The only thing to improve could be the call to Count method because causes the enumeration of numbers (so the query loses its laziness).

    Anyway I'm sure this could fit your linqness requirements.

    EDIT: Alternatively this is the less words version (it doesn't make use of Count method):

    public static IEnumerable> Consecutives(this IEnumerable numbers, int ranges, Func predicate)
    {
        var ordered = numbers.OrderBy(a => a);
        return ordered.Where(predicate)
                      .Select((element, i) => ordered.Skip(i * ranges).Take(ranges))
                      .TakeWhile(Enumerable.Any);
    }
    

提交回复
热议问题