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 } }
相关推荐
**LINQ 入门到精通** LINQ (Language Integrated Query,语言集成查询) 是 .NET Framework 的一项功能,它允许开发者使用一致的查询语法在各种数据源上进行操作,包括对象集合、数据库、XML 文件等。这篇教程将帮助...
LINQ使得这些操作变得简单且易于理解,同时保持了代码的可读性和维护性。 总的来说,“LINQ入门及应用”这本书不仅涵盖了LINQ的基础知识,还提供了丰富的实践案例,帮助开发者快速掌握和运用这项强大的技术。通过...
下面是一个简单的 LINQ to Objects 示例: ```csharp int[] numbers = { 1, 2, 3, 4, 5 }; var evenNumbers = from num in numbers where num % 2 == 0 select num; ``` 这段代码将找出数组中所有偶数并存储在 `...
**LINQ (Language Integrated Query) 入门到熟练掌握** LINQ是.NET Framework中的一个强大功能,它将查询语句直接集成到C#和Visual Basic等编程语言中,提供了统一的方式来处理各种数据源,如对象集合、数据库和XML...
以下是一个简单的LINQ查询示例,用于从字符串数组中筛选长度为5的元素,并将结果转换为大写: ```csharp string[] names = {"Burke", "Connor", "Frank", "Everett", "Albert", "George", "Harris", "David"}; ...
它提供了一个简单的对象模型,可以直接映射到数据库表,使得开发者可以使用C#或VB.NET的对象和方法来操作数据库。 1. 数据上下文(DataContext):它是LINQ_to_SQL与数据库交互的基础,代表了一个数据库连接,并...
本篇将针对“Linq语句参考简单入门”这一主题进行深入的探讨。 首先,LINQ允许开发者使用一种统一的查询语法来处理各种类型的数据源,如数据库、XML文档、集合等。这种语法与SQL查询类似,但更符合面向对象编程的...
LINQ(Language Integrated Query,语言集成查询)是.NET Framework中的一个强大特性,它为C#和Visual Basic等编程语言提供了内建的查询能力,使得数据查询如同操作本地集合一样简单。这篇教程面向初学者,旨在帮助...
**LINQ to XML 入门教程** LINQ (Language Integrated Query) 是.NET Framework中的一个强大特性,它将查询表达式直接集成到C#和Visual Basic等编程语言中,简化了数据查询的过程。其中,LINQ to XML是针对XML文档...
**Linq入门学习中文教程** Linq(Language Integrated Query,语言集成查询)是.NET Framework 3.5引入的一项重要技术,它为C#和Visual Basic等编程语言提供了强大的数据查询能力,使得开发者能够以更直观、简洁的...
LINQ(Language Integrated Query,语言集成查询)是.NET框架中的一项创新技术,它为C#和VB.NET等编程语言提供了内建的查询能力,使得数据查询如同操作数组和集合一样简单。本教程主要关注LINQ to SQL,这是一种针对...
随着对LINQ的深入理解和应用,你会发现它对于处理数据的强大能力,无论是简单的数据操作还是复杂的业务逻辑,都能游刃有余。 总的来说,这个“Linq入门到精通讲课实例”是一个极好的学习资源,通过它,你可以从零...
` 这段代码就是一个简单的LINQ查询,它将获取所有非静态的`string`类型的方法名。 在上述示例中,`var`关键字被用来声明一个匿名类型,编译器会根据上下文推断出实际类型,这里`result`是`IEnumerable<MethodInfo>`...
标题中的"Linq入门笔记学习指南"是指针对C#编程语言中的Language Integrated Query(LINQ)技术的学习资料,适合初学者。描述中提到的内容旨在帮助新手更轻松地掌握LINQ的基本概念和用法。 LINQ是一种在.NET ...
例如,一个简单的LINQ查询可能如下所示: ```csharp var query = from customer in customers where customer.City == "New York" select customer; ``` 这个查询将筛选出所有来自纽约的客户。 **五、LINQ的优势*...
### LINQ的基础入门与详细使用方法 #### 一、LINQ概述 LINQ(Language Integrated Query)是微软在.NET Framework 3.5中引入的一种强大的查询技术,它将查询功能直接融入C#语言中,使得数据操作如同编写普通代码...
C# 3.0 林林总总的 LINQ(Language Integrated ...这个入门系列涵盖了LINQ的基础用法,从简单的查询到复杂的聚合和连接操作,通过学习这一系列教程,开发者将能够熟练地在C#中运用LINQ进行数据操作,提升开发效率。
在本篇详解LINQ入门的下篇中,我们将深入探讨如何利用LINQ操作.NET开发中常见的对象,如DataSet、DataTable和DataRow。 首先,使用LINQ操作DataSet时,我们需要引入两个关键的命名空间:`System.Data`和`System....