(C#基础)Linq学习理解
一遍学习基础,一遍练习打字,很多乐趣。
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection; namespace dazilianxi
{
public class Category
{
public int Id { get;set;}
public string Name { get; set; }
}
public class Product {
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
public DateTime BuyDate { get; set; }
public decimal Price { get; set; } public override string ToString()
{
return string.Format("编号:{0},名称:{1},类别:{2},购买时间:{3},价格{4}",Id,Name,Category.Name,BuyDate,Price); }
}
public static class ProductHelper
{
public static IEnumerable<Product> GetProducts()
{
Category cat1 = new Category();
cat1.Id = ;
cat1.Name = "数码电子";
Category cta2 = new Category();
cta2.Id = ;
cta2.Name = "服饰类"; List<Product> list = new List<Product>()
{
new Product(){ Id=,Name="数码相机",Price=1899M,BuyDate=new DateTime(,,),Category=cat1
},
new Product(){Id=,Name="录像机",Price=1000M,BuyDate=new DateTime(,,),Category=cat1},
new Product(){Id=,Name="体恤衫",Price=150M,BuyDate=new DateTime(,,),Category=cta2},
new Product(){Id=,Name="夹克衫",Price=180M,BuyDate=new DateTime(,,),Category=cta2}
};
return list;
}
} public class ProductComparer : IComparer<Product>, IEqualityComparer<Product>//居然要具体的类
{
public int Compare(Product x, Product y)
{
if (x == y)//如果类别名称相同就比较产品价格
{
return x.Price.CompareTo(y.Price);
}
else //如果类别名称不同,比较类别的编号
{
return x.Category.Id.CompareTo(y.Category.Id);
}
} public bool Equals(Product x, Product y)
{
if (x.Category.Name == y.Category.Name)
{
return true;
}
else
{
return false;
}
} //这个是接口里的,一定要实现
public int GetHashCode(Product obj)
{
return obj.GetHashCode();
}
} public class PropertyComparer<T> : IEqualityComparer<T>
{
//需要比较的属性的PropertyInfo
private PropertyInfo _PropertyInfo; //通过构造函数把需要比较的属性传进来
public PropertyComparer(string propertyName)
{
_PropertyInfo = typeof(T).GetProperty(propertyName,BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.Public);//原来这个地方也可以有几个选项| 神了
if (_PropertyInfo == null)
{
throw new ArgumentException(string.Format("{0} 不是{1}的属性", propertyName, typeof(T)));
}
} public bool Equals(T x, T y)
{
object xValue = _PropertyInfo.GetValue(x, null);
object yValue = _PropertyInfo.GetValue(y, null); //如果xValue的属性值为null,那yValue的属性值也必须是null,才返回true
if (xValue == null)
return yValue == null;
return xValue.Equals(yValue);
} public int GetHashCode(T obj)
{
object propertyValue = _PropertyInfo.GetValue(obj, null);
if (propertyValue == null)
return ;
else
{
return propertyValue.GetHashCode();
}
}
}
}
var query = ProductHelper.GetProducts().OrderBy(x=>x.Id).OrderBy(b=>b.BuyDate).OrderByDescending(c=>c.Category.Id).ThenBy(p=>p.Price);
showConsole(query);
var query2 = ProductHelper.GetProducts().Select((x, index) => new { name=x.Name,index=index});//这里用到了一个匿名对象
foreach(var item in query2){
Console.WriteLine("名称:{0},索引{1}",item.name,item.index);
}
var query3 = ProductHelper.GetProducts().OrderBy(x => x, new ProductComparer());
showConsole(query3);
List<int> list = new List<int>()
{
, ,,,,,,,,,,
};
var query4 = list.Skip().Take();
showConsole<int>(query4);
Console.WriteLine("-------");
var query5 = list.TakeWhile(x => x <= ).TakeWhile(x => x > );//
showConsole(query5);
Console.WriteLine("-------");
var query6 = list.TakeWhile(x => x <= ).Where(x => x > );//3,2,3,4,5
showConsole(query6);
Console.WriteLine("-------");
var query7 = list.TakeWhile(x => x <= ).Where(x => x > ).Distinct();//3,2,4,5 去重
showConsole(query7);
Console.WriteLine("-------");
int[] arr1 = { , , , };
int[] arr2 = { , , };
var query8 = arr1.Intersect(arr2);//取交集2,3
showConsole<int>(query8);
Console.WriteLine("-------");
var query9 = arr1.Except(arr2);//Except()获取第一个集合中有,而第二个集合中没有的元素 0,1
showConsole<int>(query9);
Console.WriteLine("-------");
var query10 = arr1.Concat(arr2); //Concat()将2个集合串联起来,不剔除重复元素
showConsole<int>(query10);
Console.WriteLine("-------");
var query11 = arr1.Union(arr2); //Union()将2个集合串联起来,剔除重复元素
showConsole<int>(query11);
Console.WriteLine("-------");
//Zip()合并2个集合中位置相同的元素,将2个元素的操作结果返回一个新的元素。如果两个集合的长度不相等,以长度短的为准。
int[] arr11 = { , };
string[] arr22 = { "星期一", "星期二", "星期三" };
var query12 = arr11.Zip(arr22, (x, y) => String.Format("{0},{1}", x, y));
showConsole<string>(query12); private static void showConsole<T>(IEnumerable<T> list)
{
foreach (T item in list)
{
Console.WriteLine(item.ToString());
}
}
总结:
● 一般性的条件筛选:Where()
● 返回具体的集合类型再进行链式操作:OfType()
● 非泛型集合转换成泛型集合后再使用LINQ操作符:Cast()
● 排序、链式排序:OrderBy(), ThenBy(),实现IComparer<T>接口可以自定义排序规则
● 投影:Select()
● 返回前N个,跳过N个,分页:Take()和Skip()
● 返回符合/不符合条件,但不执行完遍历:TakeWhile()和SkipWhile()
● 反转集合元素:Reverse()
● 空集合处理:DefaultIfEmpty()
● 剔除集合中的重复元素:Distinct(),实现IEqualityComparer<Category>可自定义相等规则,针对某具体类或写一个泛型方法
● 分组以及分组后投影:GroupBy()
● 2个集合的交集:Intersect()
● 2个集合的查集:Except()
● 2个集合的串联:Concat()和Union()
● 2个集合的合并:Zip()
来源于:http://www.cnblogs.com/darrenji/p/3638561.html
http://www.cnblogs.com/darrenji/p/3638788.html
http://www.cnblogs.com/darrenji/p/3647823.html
非常基础的知识点,只有实践一次,才真的明白。
(C#基础)Linq学习理解的更多相关文章
- .Net程序员之Python基础教程学习----列表和元组 [First Day]
一. 通用序列操作: 其实对于列表,元组 都属于序列化数据,可以通过下表来访问的.下面就来看看序列的基本操作吧. 1.1 索引: 序列中的所有元素的下标是从0开始递增的. 如果索引的长度的是N,那么所 ...
- (转)Linq学习笔记
写在前面 最近在看Linq,在博客园看到这篇文章,写的通俗易懂,转来和大家一起做个分享.原文地址http://www.cnblogs.com/goscan/archive/2011/05/05/Lin ...
- C#之Linq学习笔记【转】
写在前面 其实在09年就已经学习过Linq了,并被她那优美的语法所吸引,只是现在所在的公司还在使用VS2005在.Net2.0的框架下面的开发,所以Linq也很久没有用过了,最近看部门的同事对这个有些 ...
- 零基础如何学习java更有效呢?
零基础学java,不知道该如何入手?也不知道学习的方向,很多人会问零基础怎么样学习,有没有什么入门的书籍推荐:只要方法正确,零基础学好java也是有机会的哦. 一.理解Java思想 Java是一门面向 ...
- LINQ to XML LINQ学习第一篇
LINQ to XML LINQ学习第一篇 1.LINQ to XML类 以下的代码演示了如何使用LINQ to XML来快速创建一个xml: public static void CreateDoc ...
- LINQ学习系列-----1.3 扩展方法
这篇内容继续接着昨天的Lambda表达式的源码继续下去.昨天讲了Lambda表达式,此篇讲扩展方法,这两点都是Linq带来的新特性. 一.扩展方法介绍 废话不多说,先上源码截图: 上图中Ge ...
- face recognition[翻译][深度学习理解人脸]
本文译自<Deep learning for understanding faces: Machines may be just as good, or better, than humans& ...
- 20145308 《网络对抗》Web安全基础实践 学习总结
20145308 <网络对抗> Web安全基础实践 学习总结 实验内容 本实践的目标理解常用网络攻击技术的基本原理.Webgoat实践下相关实验. 基础问题回答 (1)SQL注入攻击原理, ...
- 20145308 《网络对抗》 逆向及BOF基础实践 学习总结
20145308 <网络对抗> 逆向及BOF基础实践 学习总结 实践目的 通过两种方法,实现程序能够运行原本并不会被运行的代码 实践原理 利用foo函数的Bof漏洞,构造一个攻击输入字符串 ...
随机推荐
- [c/c++]指针(3)
在指针2中提到了怎么用指针申配内存,但是,指针申配的内存不会无缘无故地 被收回.很多poj上的题都是有多组数据,每次地数组大小会不同,所以要重新申请 一块内存.但是原来的内存却不会被收回,也是说2.3 ...
- FJUT 奇怪的数列(线性选择算法)题解
题意:找出无需数列中位数(偶数为两个中位数平均数向下取整) 思路:用nth_element(a + first,a + k,a+ end + 1)找出中位数,复杂度一般为O(n).这个STL能将 [ ...
- Harmonic Number (调和级数+欧拉常数)题解
Harmonic Number In mathematics, the nth harmonic number is the sum of the reciprocals of the first n ...
- [SpringBoot] - 发送带附件的邮件
<!--发送email依赖--> <dependency> <groupId>org.springframework.boot</groupId> &l ...
- BZOJ 1003: [ZJOI2006]物流运输(spfa+dp)
http://www.lydsy.com/JudgeOnline/problem.php?id=1003 题意: 思路: 首先用spfa计算一下任意两天之内的最短路,dis[a][b]表示的就是在第a ...
- js delete可以删除对象属性及变量
,对象属性删除 function fun(){ this.name = 'mm'; } var obj = new fun(); console.log(obj.name);//mm delete o ...
- Java中一种无意识的递归
来自: Java编程思想P287 public class Main { /** * @param args */ @Override public String toString() { retur ...
- Linux 设置程序开机自启动 (命令systemctl 和 chkconfig用法区别比较)
之前在Linux centos 7 上安装了apache 和mysql,当时并没有设置开机自动启动. 最近又重新练习网页,每次开机总是要手动启动httpd和mysqld,不方便,就想设置成开机自动启动 ...
- 雷林鹏分享:C# 委托(Delegate)
C# 委托(Delegate) C# 中的委托(Delegate)类似于 C 或 C++ 中函数的指针.委托(Delegate) 是存有对某个方法的引用的一种引用类型变量.引用可在运行时被改变. 委托 ...
- 20170503xlVBA房地产数据分类连接
Sub NextSeven_CodeFrame4() Application.ScreenUpdating = False Application.DisplayAlerts = False Appl ...