List<int> num = new List<int>{5,11,4,1,10,7}可否用Linq统计  任意两个元素差值 = 1 的个数

解决方案 »

  1.   

    LINQ是用来查询的,不是用来统计的
    至少看不出你这个小算法为什么非要用LINQ实现
      

  2.   

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> num = new List<int> { 5, 11, 4, 1, 10, 7 };
                num = num.OrderBy(x => x).ToList();
                var query = Enumerable.Range(1, num.Count - 1).Select(i => num[i] - num[i - 1]).Where(x => x == 1).Count();
                Console.WriteLine(query);
            }
        }
    }
    2
      

  3.   

    如果按照简单地循环遍历“算法”,可以写:using System;
    using System.Collections.Generic;
    using System.Linq;namespace ConsoleApplication1
    {
        class Program
        {
            static void Main(string[] args)
            {
                List<int> num = new List<int> { 5, 11, 4, 1, 10, 7 };
                var query = from x in num
                            from y in num
                            where x + 1 == y
                            select x;
                Console.WriteLine(query.Count());
                Console.ReadKey();
            }
        }
    }
      

  4.   


    主要看lz的需求了,lz问了一个似是而非的问题。比如
    3 3 4 4
    这个统计出来到底是1个,2个还是4个呢?