Linq的基本用法一

用法一:

        // 用Where筛选小于5的数据
        public static void Sample1()
        {
            int[] numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };     
            var fnums = numbers.Where(n => n < 5);

            Console.WriteLine("Numbers < 5");
            foreach (int x in fnums)
            {
                Console.WriteLine(x);
            }
        }
        // First返回第一次匹配的数据
        public static void Sample2()
        {
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };      
            string v = strings.First(s => s[0] == 'o');
            Console.WriteLine("string starting with 'o': {0}", v);
        }
        // Select筛选指定索引的数据
        public static void Sample3()
        {
            int[] numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var snums = numbers.Select(n => strings[n]);
            Console.WriteLine("Numbers");
            foreach (string s in snums)
            {
                Console.WriteLine(s);
            }
        }
        // Select筛选指定数据,返回对象
        public static void Sample4()
        {
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var q = strings.Select(s => new { Head = s.Substring(0, 1), Tail = s.Substring(1) });
            foreach (var p in q)
            {
                Console.WriteLine("Head = {0}, Tail = {1}", p.Head, p.Tail);
            }
        }
        // Where和Select结合
        public static void Sample5()
        {
            int[] numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var q = numbers.Where(n => n < 5).Select(n => strings[n]);
            Console.WriteLine("Numbers < 5");
            foreach (var x in q)
            {
                Console.WriteLine(x);
            }
        }
        // ToList方法
        public static void Sample6()
        {
            // Sequence operators form first-class queries are not executed until you enumerate them.
            int[] numbers = new[] { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };
            int i = 0;
            var q = numbers.Select(n => ++i);
            // Note, the local variable 'i' is not incremented until each element is evaluated (as a side-effect).
            foreach (var v in q)
            {
                Console.WriteLine("v = {0}, i = {1}", v, i);
            }
            Console.WriteLine();
             Methods like ToList() cause the query to be executed immediately, caching the results
            int i2 = 0;
            var q2 = numbers.Select(n => ++i2).ToList();
            // The local variable i2 has already been fully incremented before we iterate the results
            foreach (var v in q2)
            {
                Console.WriteLine("v = {0}, i2 = {1}", v, i2);
            }
        }
        // OrderBy 排序
        public static void Sample7()
        {
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var q = strings.OrderBy(s => s);  // order the strings by their name
            foreach (string s in q)
            {
                Console.WriteLine(s);
            }
        }
        // GroupBy 分组后再选择
        public static void Test()
        {
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var q = strings.GroupBy(s => s[0]); // <- group by first character of each string

            foreach (var g in q)
            {
                Console.WriteLine("Group: {0}", g.Key);
                foreach (string v in g)
                {
                    Console.WriteLine("\tValue: {0}", v);
                }
            }
        }
        // GroupBy 分组后筛选
        public static void Sample8()
        {
            string[] strings = new[] { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };  
            var q = strings.GroupBy(s => s[0]).Select(g => new { FirstChar = g.Key, Count = g.Count() });
            foreach (var v in q)
            {
                Console.WriteLine("There are {0} string(s) starting with the letter {1}", v.Count, v.FirstChar);
            }
        }
        class Person
        {
            public string Name { get; set; }
            public int Level { get; set; }
        }

        static Person[] persons = new Person[] {
        new Person {Name="Jesper", Level=3},
        new Person {Name="Lene", Level=3},
        new Person {Name="Jonathan", Level=5},
        new Person {Name="Sagiv", Level=3},
        new Person {Name="Jacqueline", Level=3},
        new Person {Name="Ellen", Level=3},
        new Person {Name="Gustavo", Level=9}
        };
        // Group by分组
        public static void Sample10()
        {
            var q = from p in persons
                    orderby p.Level, p.Name
                    group p.Name by p.Level into g
                    select new { Level = g.Key, Persons = g };
            foreach (var g in q)
            {
                Console.WriteLine("Level: {0}", g.Level);
                foreach (var p in g.Persons)
                {
                    Console.WriteLine("Person: {0}", p);
                }
            }
        }
        // OrderBy和ThenBy分组
        public static void Sample9()
        {
            var q = persons.OrderBy(p => p.Level).ThenBy(p => p.Name);

            foreach (var p in q)
            {
                Console.WriteLine("{0}  {1}", p.Level, p.Name);
            }
        }


 ToArray() 和ToList()

       // 为了显示需要对结果做一份缓存的copy
        // 不加ToArray()
        public static void DemoA()
        {
            string[] strings = { "Lily", "Cookie", "Shalary" };
            var q = strings.Where(s => s[0] == 'L');
            foreach (var w in q)
            {
                Console.WriteLine(w);
            }
            // 改变初始值
            strings[0] = "john";
            foreach (var w in q)
            {
                Console.WriteLine(w);
            }
            Console.Read();
        }
        // 加ToArray
        public static void DemoB()
        {
            string[] strings = { "Lily", "Cookie", "Shalary" };
            var q = strings.Where(s => s[0] == 'L').ToArray();
            foreach (var w in q)
            {
                Console.WriteLine(w);
            }
            // 改变初始值
            strings[0] = "john";
            foreach (var w in q)
            {
                Console.WriteLine(w);
            }
            Console.Read();
        }
        // ToArray方法
        public static void ToArray()
        {
            double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };

            var sortedDoubles =

                from d in doubles

                orderby d descending

                select d;

            var doublesArray = sortedDoubles.ToArray();
            Console.WriteLine("Every other double from highest to lowest:");

            for (int d = 0; d < doublesArray.Length; d += 2)
            {

                Console.WriteLine(doublesArray[d]);

            }
        }

        // ToList示例
        public static void ToList()
        {

            string[] words = { "cherry", "apple", "blueberry" };

            var sortedWords =

                from w in words

                orderby w descending

                select w;

            var wordList = sortedWords.ToList();

            Console.WriteLine("The sorted word list:");

            foreach (var w in wordList)
            {

                Console.WriteLine(w);

            }

        }

OfType和Dictionary

  public static void ToDictionary()
        {
            var scoreRecords = new[] { new {Name = "Alice", Score = 50},
                                new {Name = "Bob" , Score = 40},
                                new {Name = "Cathy", Score = 45}
                              };
            var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
            Console.WriteLine("Bob's score: {0}", scoreRecordsDict["Bob"]);
        }
        public static void OfType()
        {
            object[] numbers = { null, 1.0, "two", 3, 4.0f, 5, "six", 7.0 };
            var doubles = numbers.OfType<double>();
            Console.WriteLine("Numbers stored as doubles:");
            foreach (var d in doubles)
            {
                Console.WriteLine(d);
            }
        }



 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值