Linq的好处在于,使用语句筛选的时候并不会立刻将结果取出来(占用内存资源),而是使用的时候才能提取。
命名空间:System.Linq;
由于Linq实现了IEnumerable接口,所以 .NetFrameWork框架下的所有集合对象都可以使用Linq进行操作。
//准备一个被操作的数组
int[] tmp= { 11, 18, 19, 30, 25, 34, 59, 77, 26, 31, 94 };
//查询这组数组中能被2整除,并且能被5整除的数
var numQurey = from num in tmp where num % 2 == 0 && num % 5 == 0 orderby num select num;
for (int i = 0; i < numQurey2.Count(); i++)
{
Console.WriteLine(numQurey2.ToArray()[i].ToString()); //打印
}
orderby:升序排序
ascending:降序排列
//自定义一个类,这个类包含名字、城市(后面会通过所在城市分组)
public class Custom
{
public string Name { get; set; }
public string City { get; set; }
}
public static void Main(string[] args)
{
List customList = new List();
customList.Add(new Custom() { Name = "Peter", City = "NewYork" });
customList.Add(new Custom() { Name = "jerry", City = "Tokyo" });
customList.Add(new Custom() { Name = "Lili", City = "NewYork" });
customList.Add(new Custom() { Name = "Jack", City = "NewYork" });
customList.Add(new Custom() { Name = "WangMeiMei", City = "Tokyo" });
//group by :根据键值将数组分组
var qureyCustom = from custom in customList
group custom by custom.City;
foreach (var items in qureyCustom)
{
//符合城市名检索的Custon对象成员
Console.WriteLine(items.Key);
foreach (var item in items)
{
//成员名字
Console.WriteLine(" {0}", item.Name);
}
}
}
group by :通过键值将数组分组。
string[] strList = {"Hark. I hear the returning footsteps of my love"};
var strQurey = from list in strList //数据源
let newStrs = list.Split(' ') //截取空格,成为一个新的数组
from newStr in newStrs //将新的数组作为数据源
let totalStr = newStr.ToUpper() //转换为大写
select totalStr; //输出
foreach (var item in strQurey)
{
Console.WriteLine(item.ToString());
}
Let:替换原有的集合为新集合
Split (‘a’) :截取‘a’这个字符
ToUpper ():转换为大写
PS: Where
public static IEnumerableWhere (this IEnumerable source, Func predicate);
在Where<>中主要分为两部分:
- IEnumerable<>:Where方法就可以实现IEnumerable<>的每一个类型,比如:List<>,string[]等。
- Func
:这个委托将判断T是否满足条件,然后返回bool类型,如果满足则将T放入目标集合中。
下面代码用来判断一组客户信息中是否有 “Peter” “Tony”:
////// 客户信息类 /// public class Custom { public string Name { get; set; } public string City { get; set; } } public class Program { static void Main(string[] args) { ListctmList = new List () { new Custom(){Name="Peter",City="Tokyo"}, new Custom(){Name="Jerry",City="BeiJing"}, new Custom(){Name="Allen",City="ShangHai"}, new Custom(){Name="Tony",City="NewYork"}, new Custom(){Name="Lee",City="GaungZhou"}, }; IEnumerable customs = ctmList.Where (custom => custom.Name == "Peter" || custom.Name == "Tony"); foreach (Custom item in customs) { Console.WriteLine(item.Name+" : "+item.City); } } }
【END】



