Finding Consecutive Items in List using Linq

后端 未结 4 1426
借酒劲吻你
借酒劲吻你 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条回答
  •  旧时难觅i
    2020-12-18 05:22

    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 };
    
    var numbersQuery = numbers.Select((x, index) => new { Index = index, Value = x});
    
    var query = from n in numbersQuery
                from n2 in numbersQuery.Where(x => n.Index == x.Index - 1).DefaultIfEmpty()
                from n3 in numbersQuery.Where(x => n.Index == x.Index - 2).DefaultIfEmpty()
                where n.Value > 10
                where n2 != null && n2.Value > 10
                where n3 != null && n3.Value > 10
                select new
                {
                  Value1 = n.Value,
                  Value2 = n2.Value,
                  Value3 = n3.Value
                };
    

    In order to specify which group, you can call the Skip method

    query.Skip(1)
    

提交回复
热议问题