LINQ简单的入门

 

LINQ简单的入门
 

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Linq.Expressions;
 
namespace LinQ
{
    public partial class Form1 : Form
    {
        /// <summary>
        /// <Author>jilongliang</Author>
        /// <Date>2012/8/14</Date>
        /// <Language>CSharp</Language>
        /// <From>http://www.java2s.com/</From>
        /// </summary>
        public Form1()
        {
            InitializeComponent();
        }
 
        private void btnTest1_Click(object sender, EventArgs e)
        {
            string[] presidents = { "A", "Ar", "B", "Bu", "C", "Cleveland" };
            /*
             *=>是lambda表达式在JDK8好像也支持这个语法
             *Where并不是string里面的方法而是 Enumerable里面的
             *IEnumerable是一个公开的枚举
             *p.StartsWith的寻找到字符串第一个C就输出
             */
            IEnumerable<string> sequence = presidents.Where(p => p.StartsWith("C"));
            foreach (string s in sequence)
                txtTest1.Text += string.Format("{0}", s);
 
        }
 
        private void btnTest2_Click(object sender, EventArgs e)
        {
            IEnumerable<char> query = "I Love Sports T!";
            /*
             * 经过测试!=这个符号c!='T'意思就是循环到包括有t的字符串就去掉t之后,
             * 再输出剩下来循环到的字符串
             * c=='T'的意思寻找到t就把所有都输出
             * 
             */
            query = query.Where(c => c != 'T');//
 
            foreach (char c in query)
            {
                txtTest2.Text += string.Format("{0}", c);
            }
        }
 
        private void btnTest3_Click(object sender, EventArgs e)
        {
            string[] names = { "A123123", "B123", "C123123", "E123", "W" };
            //循环字符串长度小于六的长度
            IEnumerable<string> sequence = from n in names
                                           where n.Length < 6
                                           select n;
 
            foreach (string name in sequence)
            {
                textTest3.Text += string.Format("{0}", name);
            }
        }
 
        private void btnTest4_Click(object sender, EventArgs e)
        {
            /**
             * Aa Bb Cc Dd Ee Ff Gg Hh Ii Jj Kk Ll Mm
             * Nn Oo Pp Qq Rr Ss Tt Uu Vv Ww Xx Yy Zz
             */
            String[] Query = { "One", "Two", "Three", "Four", "Five",
              "Six", "Seven", "Eight", "Nine", "Ten" };
            /**
             * 找到字符串第一个字母(StringValue.Substring(0, 1))大于A的就输出,
             * 并且按照这个字母进行排序orderby IndexValue
             */
            var query = from StringValue in Query
                        let IndexValue = StringValue.Substring(0, 1)
                        where Convert.ToChar(IndexValue) > 'A'
                        orderby IndexValue
                        select new { StringValue, IndexValue };
 
            foreach (var ThisValue in query)
 
                txtTest4.Text += string.Format("{0}", ThisValue.IndexValue
                    + " - " + ThisValue.StringValue);
 
        }
 
        private void btnTest5_Click(object sender, EventArgs e)
        {
            List<ProductWithNullablePrice> products = ProductWithNullablePrice.GetSampleProducts();
            foreach (ProductWithNullablePrice product in products.Where(p => p.Price == null))
            {
                txtTest5.Text += product.Name;
            }
        }
 
        #region
        private class ProductWithNullablePrice
        {
            public string Name { get; private set; }
            public decimal? Price { get; private set; }//这个?的意思就是允许插入数据库为Null值
 
            public ProductWithNullablePrice(string name, decimal price)
            {
                Name = name;
                Price = price;
            }
            //无参数构造方法
            ProductWithNullablePrice()
            {
            }
 
            public static List<ProductWithNullablePrice> GetSampleProducts()
            {
                return new List<ProductWithNullablePrice>
                {
                    new ProductWithNullablePrice { Name="C", Price= 9.99m },
                    new ProductWithNullablePrice { Name="A", Price= 4.99m },
                    new ProductWithNullablePrice { Name="F", Price= 3.99m },
                    new ProductWithNullablePrice { Name="S", Price=null }
                };
            }
            /// <summary>
            /// 重写
            /// C#中重写(override)和重载(overload)
            /// <URL>http://www.cnblogs.com/forward/archive/2009/02/16/1391976.html</URL>
            /// </summary>
            /// <returns></returns>
            public override string ToString()
            {
                return string.Format("{0}: {1}", Name, Price);
            }
        }
        #endregion
 
        private void btnTest6_Click(object sender, EventArgs e)
        {
            // LinqArrayLength();
            //GetIntersect();
            //GetFilter();
            //FilterArrayOfInts();
            //GetLookUp();
            //GetAggregate();
            //GetAggregate_Factorial();
            //GetAggregateRang();
            //GetLambda();
            //GetExpression();
            //GetOdd_Even();
            //GetToDictionary();
            //GetFirstOrDefault();
            //GetRepeat();
            //GetNested_Query();
            //GetDistinct();
            //GetSelectMany();
            GetSequenceEqual();
        }
 
 
        /// <summary>
        /// 使用Linq的Select处理数组的Length
        /// </summary>
        private void LinqArrayLength()
        {
 
            string[] presidents = { "A", "Ar", "Buc", "Bush", "Carte", "Clevel" };
 
            var nameObjs = presidents.Select(p => new { p, p.Length });
 
            foreach (var item in nameObjs)
                txtTest6.Text += item.ToString() + "\t";
        }
 
        /// <summary>
        /// 获取最大值
        /// </summary>
        /// <returns></returns>
        private int GetMaxValue()
        {
            int[] myInts = new int[] { 974, 2, 7, 1374, 27, 54 };
            int maxInt = myInts.Max();
            return maxInt;
        }
        /// <summary>
        /// 获取最小值
        /// </summary>
        /// <returns></returns>
        private int GetMinValue()
        {
            int[] myInts = new int[] { 974, 2, 7, 1374, 27, 54 };
            int minInt = myInts.Min();
            return minInt;
        }
        /// <summary>
        /// Intersect使用
        /// </summary>
        private void GetIntersect()
        {
 
            int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
            int[] numbersB = { 1, 3, 5, 7, 8 };
 
            var commonNumbers = numbersA.Intersect(numbersB);
            //两个数组共同拥有的数组是
            Console.WriteLine("Common numbers shared by both arrays:");
            foreach (var n in commonNumbers)
            {
                txtTest6.Text += string.Format("数组共同数字是{0}", n.ToString() + "\t");
            }
        }
 
        #region
        /// <summary>
        /// 过滤数组
        /// FilterArrayOfInts和delegate使用
        /// delegate是表示委托,委托是一种数据结构,它引用静态方法或引用类实例及该类的实例方法
        /// </summary>
        private void FilterArrayOfInts()
        {
            int[] nums = { 1, 2, 3, 4, 5, 6 };
 
            int[] oddNums = FilterArrayOfInts(nums, delegate(int i) { return ((i & 1) == 1); });
 
            foreach (int i in oddNums)
                txtTest6.Text += string.Format("FilterArrayOfInts{0}", i);
 
        }
        //定义一个bool的委托IntFilter
        public delegate bool IntFilter(int i);
        public static int[] FilterArrayOfInts(int[] ints, IntFilter filter)
        {
            ArrayList list = new ArrayList();
            foreach (int i in ints)
            {
                if (filter(i))
                {
                    list.Add(i);
                }
            }
            return ((int[])list.ToArray(typeof(int)));
        }
        #endregion
 
        #region
 
        public class Employee
        {
            public int birthYear;
            public string firstName;
            public string lastName;
 
            public static Employee[] GetEmployees()
            {
                Employee[] actors = new Employee[] 
                {
                    new Employee { birthYear = 1964, firstName = "乔", lastName = "锋" },
                    new Employee { birthYear = 1968, firstName = "黄", lastName = "蓉" },
                    new Employee { birthYear = 1960, firstName = "郭", lastName = "靖" },
                    new Employee { birthYear = 1964, firstName = "杨", lastName = "过" },
                 };
                return (actors);
            }
        }
        /// <summary>
        /// Lookup的使用
        /// </summary>
        private void GetLookUp()
        {
 
            ILookup<int, string> lookup = Employee.GetEmployees()
            .ToLookup(k => k.birthYear, a => string.Format("firstName:{0} lastName:{1}", a.firstName, a.lastName));
 
            IEnumerable<string> actors = lookup[1964];
            foreach (var actor in actors)
                txtTest6.Text = string.Format("{0}", actor);
        }
 
        #endregion
 
        /// <summary>
        ///Aggregate是使用
        ///指定一个数组求数组的数字加起来的总和
        /// </summary>
        private void GetAggregate()
        {
 
            int[] numbers = { 9, 3, 5, 4, 2, 6, 7, 1, 8 };
            //指定5个种子值用作累加器初始值
            var query = numbers.Aggregate(5, (a, b) => ((a < b) ? (a * b) : a));
            txtTest6.Text = string.Format("{0}", query + "\t");
        }
 
        /// <summary>
        /// Aggregate是使用
        /// 求指定一个数字求阶乘
        /// 6!=6*5*4*3*2*1
        /// </summary>
        private void GetAggregate_Factorial()
        {
            int N = 6;
            int agg = 0;
            IEnumerable<int> intSequence = Enumerable.Range(1, N);
            foreach (int item in intSequence)
            {
                agg = intSequence.Aggregate((av, e) => av * e);
            }
            txtTest6.Text = string.Format("{0}! = {1}", N, agg);
        }
        /// <summary>
        /// 指定一个范围的数组进行求总和
        /// </summary>
        private void GetAggregateRang()
        {
            int sum = 0;
            IEnumerable<int> intSequence = Enumerable.Range(1, 10);
            foreach (int item in intSequence)
            {
                sum = intSequence.Aggregate(0, (s, i) => s + i);
            }
            txtTest6.Text = string.Format("{0}", sum + "\t");
        }
 
 
        #region
 
        delegate int NumericSequence();
        private void GetLambda()
        {
            int seed = 1;
            NumericSequence natural = () => seed++;
            txtTest6.Text = natural().ToString();
        }
 
        #endregion
 
        #region
        private void GetSequenceEqual() {
            string[] stringifiedNums1 = { "101", "49", "017", "1080", "00027", "2" };
            string[] stringifiedNums2 = { "1", "1049", "17", "080", "27", "02" };
            bool eq = stringifiedNums1.SequenceEqual(stringifiedNums2, new MyStringifiedNumberComparer());
            txtTest6.Text = string.Format("{0}", eq);
        }
 
        public class MyStringifiedNumberComparer : IEqualityComparer<string>
        {
            public bool Equals(string x, string y)
            {
                return (Int32.Parse(x) == Int32.Parse(y));
            }
 
            public int GetHashCode(string obj)
            {
                return Int32.Parse(obj).ToString().GetHashCode();
            } 
        }
        #endregion
 
        /// <summary>
        ///  以表达式目录树的形式将强类型 lambda 表达式表示为数据结构,无法继承此类.
        ///  获取偶数与奇数的数字显示出来
        /// </summary>
        private void GetExpression()
        {
            Expression<Func<int, bool>> isOddExpression = i => (i & 1) == 1;
            ParameterExpression param = Expression.Parameter(typeof(int), "i");
            Expression<Func<int, bool>> isOdd =
                Expression.Lambda<Func<int, bool>>(
                Expression.Equal(
                  Expression.And(
                    param,
                    Expression.Constant(1, typeof(int))),
                  Expression.Constant(1, typeof(int))),
                new ParameterExpression[] { param });
 
            Func<int, bool> isOddCompiledExpression = isOddExpression.Compile();
            for (int i = 0; i < 10; i++)
            {
                if (isOddCompiledExpression(i))
                    txtTest6.Text += string.Format("{0}", i + " is odd" + "\t");
                else
                    txtTest6.Text += string.Format("{0}", i + " is even" + "\t");
            }
        }
        /// <summary>
        /// 获取偶数与奇数的数字显示出来
        /// </summary>
        private void GetOdd_Even()
        {
            //Func封装一个具有一个参数并返回 TResult 参数指定的类型值的方法
            Func<int, bool> isOddDelegate = i => (i & 1) == 1;
            for (int i = 0; i < 10; i++)
            {
                if (isOddDelegate(i))
                    txtTest6.Text += string.Format("{0}", i + " is odd" + "\t");
                else
                    txtTest6.Text += string.Format("{0}", i + " is even" + "\t");
            }
 
        }
 
        /// <summary>
        /// ToDictionary字典的使用 
        /// </summary>
        private void GetToDictionary()
        {
            var scoreRecords = new[] { 
                                new {Name = "数学", Score = 120},
                                new {Name = "英文" , Score = 140},
                                new {Name = "中文", Score = 145}
                              };
            try
            {
                var scoreRecordsDict = scoreRecords.ToDictionary(sr => sr.Name);
                //指定一个科目是否在字典里面,如果不在就报异常
                txtTest6.Text = string.Format("Bob's score: {0}", scoreRecordsDict["英文"] + "\t");
            }
            catch (Exception)
            {
                throw;
            }
 
        }
        /// <summary>
        /// 获取第一个或者默认的值
        /// </summary>
        private void GetFirstOrDefault()
        {
            string[] presidents = { "G", "H", "a", "H", "over", "Jack" };
 
            string name = presidents.FirstOrDefault(p => p.StartsWith("B"));
            txtTest6.Text = string.Format("{0}", name == null ? "NULL" : name);
        }
 
        /// <summary>
        /// 获取Repeat重复
        /// 生成包含一个重复值的序列
        /// 返回结果:
        //  一个 System.Collections.Generic.IEnumerable<T>,包含一个重复值
        /// </summary>
        private void GetRepeat()
        {
            IEnumerable<int> ints = Enumerable.Repeat(2, 10);
            foreach (int i in ints)
                txtTest6.Text = string.Format("{0}", i + "\t");
        }
        /// <summary>
        /// an untidy nested query
        /// </summary>
        private void GetNested_Query()
        {
 
            string[] names = { "Tom", "Dick", "Harry", "Mary", "Jay" };
            IEnumerable<string> query =
              Enumerable.Select(
                Enumerable.OrderBy(
                  Enumerable.Where(
                    names, n => n.Contains("a")//处理包括有a的字符串
                  ), n => n.Length
                ), n => n.ToUpper() //转换为大写
              );
 
            foreach (var q in query)
            {
                txtTest6.Text += string.Format("{0}", q + "\t"); //\t代表制8位
            }
        }
 
        /// <summary>
        /// 处理重复的数字,重复的就拿唯一D一个值
        /// </summary>
        private void GetDistinct()
        {
            int[] fl = { 2, 2, 3, 5, 5 };
            var unique= fl.Distinct(); 
            foreach (var f in unique)
            {
                txtTest6.Text += string.Format("{0}", f + "\t");
            }
        }
 
        /// <summary>
        /// 查找更多的值
        /// </summary>
        private void GetSelectMany()
        {
            string[] presidents = { "A", "Art", "Buch", "Bush", "Carter", "land" };
 
            IEnumerable<char> chars = presidents
             .SelectMany((p, i) => i < 5 ? p.ToArray() : new char[] { });
 
            foreach (char ch in chars)
                txtTest6.Text += string.Format("{0}",ch);
        }
        #region
        /// <summary>
        /// Filter过滤使用
        /// </summary>
        private void GetFilter()
        {
            List<Person> people = new List<Person> {
               new Person { ID = 1, IDRole = 1, LastName = "布斯", FirstName = "乔"},
               new Person { ID = 2, IDRole = 2, LastName = "帮主", FirstName = "乔"}
            };
            //过滤ID为1的用户
            Func<Person, bool> filter = delegate(Person p) { return p.ID == 1; };
            var query = people
                        .Where(filter)
                        .Select(p => new { p.FirstName, p.LastName });
 
            foreach (var q in query)
                txtTest6.Text += string.Format("被过滤的用户是:{0}", q.ToString() + "\t");
 
        }
 
 
        /// <summary>
        /// Preson实体类
        /// </summary>
        private class Person
        {
            int _id;
            int _idRole;
            string _lastName;
            string _firstName;
 
            public int ID
            {
                get { return _id; }
                set { _id = value; }
            }
 
            public int IDRole
            {
                get { return _idRole; }
                set { _idRole = value; }
            }
 
            public string LastName
            {
                get { return _lastName; }
                set { _lastName = value; }
            }
 
            public string FirstName
            {
                get { return _firstName; }
                set { _firstName = value; }
            }
        }
        #endregion
    }
}

 

 

 




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值