您的位置:首页 > 其它

自己学习LINQ记录(一)

2013-11-28 15:49 169 查看
其实LINQ也出来很多年了,一直没有好好学学。最近不忙就照猫画虎的学习下。还确实挺方便的。我也是参考别人的网站写的,本博客主要是自己记录下。写的不够详细。开始LINQ是.NET Framework 3.5的新特性,其全称是 Language Integrated Query,即语言集成查询,是指将查询功能和语言结合起来。从而为我们提供一种统一的方式,让我们能在C#或VB.NET语言中直接查询和操作各种数据。LINQ是用来描述数据访问总体方式的术语。LINQ to Object是针对实现了IEnumerable<T>的对象的LINQ;LINQ to SQL是针对关系数据库的LINQ;LINQ to XML是针对XML文档的LINQ。先来一个简答的例子输入几个银行的名字,输出名字为三个字母的银行。Code1:
string[] custNames = {"CCB", "ICBC", "CITIC", "BOB"};
IEnumerable<string> inquiryNames = System.Linq.Enumerable.Where(custNames, n => n.Length <=3);

foreach (var n in inquiryNames)
{
Console.WriteLine(n);
}
输出CCBBOBLINQ中最基本的数据单元是sequences和elements。一个sequence是实现了IEnumerable<T>的对象,而一个element是sequence中的每一个元素。上面的实现等价于下面这句
IEnumerable<string> inquiryNames = custNames.Where(n => n.Length <= 3);
C#还提供了另外一种书写query的语法,叫做查询表达式语法Code2:
string[] custNames = {"CCB", "ICBC", "CITIC", "BOB"};

IEnumerable<string> inquiryNames = from n in custNames where n.First() == 'C' select n;

foreach (var n in inquiryNames)
{
Console.WriteLine(n);
}
输出结果CCBCITIC查询首字母为C的银行。二连接查询运算符如果需要创建更加复杂的查询,我们可以在表达式之后添加其他查询运算符,产生一个查询链。Code3
string[] custNames = {"CCB", "ICBC", "CITIC", "BOB"};
var inquiryNames = custNames
.Where(n => n.Contains("C"))
.OrderBy(n => n)
.Select(n => n.ToLower());

foreach (var n in inquiryNames)
{
Console.WriteLine(n);
}
此例子3个条件1. 包括“C”2. 排序3. 转换成小写学习过SQL的应该比较好理解这个情况,注意写法。结果:ccbciticicbc

Lambda表达式

List<int> list1 = new List<int>();
list1.AddRange(new int[] { 1, 3, 4, 8, 10, 11 });

var temp = list1.FindAll(i => (i % 2) == 0);
foreach (var n in temp)
{
Console.WriteLine(n);
}
嵌套Lambda表达式输出结果4810并不是所有的查询运算符都返回一个sequence。元素(element)运算符会从输入sequence中获取单个元素,如:First,Last和ElementAt:
int[] numbers = { 10, 9, 8, 7, 6 };
int firstNumber = numbers.First();                  // 10
int lastNumber = numbers.Last();                    // 6
int secondNumber = numbers.ElementAt(1);            // 9
int lowestNumber = numbers.OrderBy(n => n).First(); // 6
int count = numbers.Count();    // 5
int min = numbers.Min();        // 6
bool hasTheNumberNine = numbers.Contains(9);    // truebool hasElements = numbers.Any();               // truebool hasAnOddElement = numbers.Any(n => (n % 2) == 1);  //true
int[] seq1 = { 1, 2, 2, 3 };
int[] seq2 = { 3, 4, 5 };IEnumerable<int> concat = seq1.Concat(seq2);    // { 1, 2, 2, 3, 3, 4, 5 }IEnumerable<int> union = seq1.Union(seq2);      // { 1, 2, 3, 4, 5 }
这节比较简单 不多说了 主要是习惯LINQ的写法。我是学习这位的博客 写的很好 http://www.cnblogs.com/lifepoem/archive/2011/12/16/2288017.html 
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: