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


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);
            }

  
  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值