`
jilong-liang
  • 浏览: 470735 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类

LINQ简单的入门

    博客分类:
  • 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
    }
}

 

 

 




  • 大小: 106.5 KB
  • 大小: 97.4 KB
分享到:
评论

相关推荐

    Linq语句参考(简单入门)

    Linq语句参考简单入门Linq语句参考简单入门Linq语句参考简单入门

    LINQ快速入门(很不错)

    LINQ LINQ学习 LINQ入门 LINQ_TO_SQL 本书来自于C# CORNER 英文版的(单词简单,很容易读懂)

    linq 学习 Linq To Sql 快速入门中文教程

    linq绝佳入门之经典,并搭配在项目的各种应用的讲解,简单易懂

    C#3.0与.net3.5之Linq入门

    本书为linq入门书籍,简单易懂。主要介绍了linq的基本语法及应用。

    Linq入门学习教程

    Linq入门学习教程,简单易学,很好上手

    LINQ入门教程

    LINQ的入门书籍,简单易懂,方便学习,入门必备啊。

    简单ASP.NET 3.5 LINQ 实例 学习

    ASP.NET3.5 LINQ 实例 学习 入门

    Linq to SQL入门代码

    Linq to SQL 实现的简单的添、删、改、查以及分页功能

    接触Linq必看简单教程

    1. C# 3.0 入门系列(一) 从linq开始引C# 3.0。 2. C# 3.0入门系列(二) 数据库的准备,引入Linq To Sql的准备。 3. C# 3.0入门系列(三) 第一个Linq To Sql工程。 4. C# 3.0入门系列(四)-之Select操作 ...

    MVC+LINQ进行CURD操作

    这个是简单的MVC3+LINQ进行数据库CURD的操作 适合新手入门学习

    LINQ技术详解C# 2008版.part1(分成6卷,后面的不用资源分)

     本书可以为LINQ的初学者、中级用户和高级用户等不同层次的读者提供相应的信息,不仅为LINQ初学者提供入门级的知识和实例,还可以作为LINQ中高级开发人员的工具书。 拉特兹(JOSEPH C.RATTZ,JR.)从l990年开始...

    LinQ初体验

    初学LinQ一个简单的入门例子,让你感受LinQ的魅力

    C# webservice linq

    webservice C# 简单入门例子,linq应用,sqlserver2005

    详解LINQ入门(中篇)

    在上篇中简单的和大家提到了LINQ具有一个很有意思的特性那就是“延迟加载”(或“延迟计算”),什么是延迟加载呢?先看来自官方的描述:延迟执行意味着表达式的计算延迟,直到真正需要它的实现值为止。是不是觉得...

    ASP.NET3.5入门经典:涵盖C#和VB.NET(第5版)pdf

    《ASP.NET3.5入门经典-涵盖C#和VB.NET》以建立一个实际的Web站点为主线,从最初的没有任何功能的简单站点开始,然后逐步增加功能和效果,直到最后建立一个完整的、功能丰富的、数据库驱动的、交互的Web站点。...

    linq-to-sql-分布式事务处理.rar

    linq-to-sql-分布式事务处理,简单明了的 事务入门,从简单事务到分布式事务,清晰易懂,很好的入门资料

    C#入门经典(第4版)中文版高清PDF【共16个分卷】.part14

    中文名: C#入门经典(第4版) 原名: Beginning Microsoft Visual C# 2008 作者: (美)沃森(Watson K.) (美)内格尔(Nagel C.) 译者: 齐立波 出版社: 清华大学出版社 目录: 第1部分 C#语言 第1章 C#简介 第2章 编写C#...

    ASP.NET 3.5入门经典--涵盖C#和VB.NET(Wrox)

    本书以建立一个实际的Web站点为主线,从最初的没有任何功能的简单站点开始,然后逐步增加功能和效果,直到最后建立一个完整的、功能丰富的、数据库驱动的、交互的Web站点。其间,分别介绍了建立这个Web站点涉及到的...

    ASP.NET3.5从入门到精通基于C#2008.pdf

    这是一本非常好的ASP.NET入门书籍。本书以建立一个实际的Web站点为主线,从最初的没有任何功能的简单站点开始,然后逐步增加功能和效果,直到最后建立一个完整的、功能丰富的、数据库驱动的、交互的Web站点。其间,...

Global site tag (gtag.js) - Google Analytics