使用linq操控数组的一些小方法

来源:互联网 发布:淘宝填写退货物流信息 编辑:程序博客网 时间:2024/06/06 06:34
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Collections;namespace ConsoleApplication20{    class Program    {        static void Main(string[] args)        {            test.test6();        }    }    class test    {        ///         /// 使用 lastOrDefault方法返回数组最后一个元素        ///         public static void test1()        {            string[] s = new string[] { "星辰", "日月", "清泉", "高山", "流水", "草木", "星辰2" };            string ienumer = s.LastOrDefault(p => p.StartsWith("白"));            Console.WriteLine(ienumer);        }        public static void test2()        {            string[] s = new string[] { "星辰", "日月", "清泉", "高山", "流水", "草木", "星辰2" };            //string i = s.Single(p=>p.StartsWith("日"));            string i = s.SingleOrDefault(p=>p.StartsWith("日"));            string si = s.Where(p => p.Length == 10).SingleOrDefault();            Console.WriteLine(si==null ? "null":si);        }        public static void test3()        {            string[] s = new string[] { "星辰", "日月", "清泉", "高山", "流水", "草木", "星辰2" };            //IEnumerable i = s.Cast();            //string si = i.ElementAt(3); Console.WriteLine(si);            s.Contains("xingchen");//匹配项            Console.WriteLine(s.ElementAt(2));        }        public static void test4()        {            string[] s = new string[] { "星辰", "日月", "清泉", "高山", "流水", "草木", "星辰2" };            Console.WriteLine(s.Count(p => p.StartsWith("星辰")));            Console.WriteLine(s.Max(p=>p.StartsWith("2")));        }        public static void test5()        {            int[] i = new int[] { 1,2,3,4,5,6,7,8,9,10};            Console.WriteLine(i.Sum());            Console.WriteLine(i.Max());        }        ///         /// 阶乘        ///         public static void test6()        {            int n = 5;            IEnumerable test = Enumerable.Range(1, n);            int count = test.Aggregate((s1,s2)=>s1*s2);            Console.WriteLine(count);        }    }}
将数组转化为IEnumerable
 string[] mystring = {"1","21","3","4","5"};            IEnumerable isstring = mystring.Where(s=>s.Length==2);//将数组转化为IEnumerable进行查询            Console.WriteLine("After where is");            foreach (string s in isstring)            {                Console.WriteLine(s);            }
原创粉丝点击