首页 > 代码库 > Linq练习
Linq练习
首先在Program.cs的Main()方法下添加如下代码:
string[] names = { "heh", "haha", "huahua", "kuku" };
1、取得以h开头的名称:
(查询语法)
var queryResult = from n in names
where n.StartsWith("h")
select n;
(方法语法)
var queryResult = names.Where(n => n.StartsWith("h"));
2、将查询结果排序 (降序):
(查询语法,由于首字母一样,所以按第二个字母的顺序进行降序)
var queryResult = from n in names
where n.StartsWith("h")
orderby n descending
select n;
(方法语法)
var queryResult = names.Where(n=>n.StartsWith("h")).OrderByDescending(n=>n);
在Main()方法中添加如下代码:
int[] numbers = {2,4,5,1,55,11,32,134,11,333,245 };
1、找出大于100的数:
(查询语法)
var queryResult = from n in numbers
where n > 100
select n;
(方法语法)
var queryResult = numbers.Where(n=>n>100);
2、分别输出结果的个数,结果中的最小值,结果中的最大值,数字结果的平均值,所有数字结果的总和:
Console.WriteLine("结果的个数:"+queryResult.Count());
Console.WriteLine("结果中的最小值:"+queryResult.Min());
Console.WriteLine("结果中的最大值:"+queryResult.Max());
Console.WriteLine("结果中的平均值:"+queryResult.Average());
Console.WriteLine("数字结果的总和:"+queryResult.Sum());
查询复杂对象,在Program类的开头,给Customer类添加如下类定义:
class Customer
{
public string ID { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string Region { get; set; }
public decimal Sales { get; set; }
public override string ToString()
{
return "ID:" + ID + "City:" + City + "Country:" + Country + "Region:" + Region + "Sales:" + Sales;
}
}
在Main()方法中添加如下代码:
List<Customer> customers = new List<Customer> {
new Customer{ID="A",City="New York1",Country="USA1",Region="North1",Sales=111},
new Customer{ID="B",City="New York2",Country="USA2",Region="North2",Sales=222},
new Customer{ID="C",City="New York3",Country="USA3",Region="North3",Sales=333},
new Customer{ID="D",City="New York4",Country="USA4",Region="North4",Sales=444},
new Customer{ID="E",City="New York5",Country="USA5",Region="North5",Sales=555},
new Customer{ID="F",City="New York6",Country="USA6",Region="North6",Sales=666},
new Customer{ID="G",City="New York7",Country="USA7",Region="North7",Sales=777}
};
1、选择来自North1的顾客:
(查询语法)
var queryResults = from c in customers
where c.Region == "North1"
select c;
(方法语法)
var queryResults = customers.Where(n=>n.Region=="North1");
2、投射--在查询中创建新的对象:
(查询语法)
var queryResults = from c in customers
where c.Region == "North7"
select new {c.City,c.Country,c.ID };
(方法语法,在查询语法中需要select子句,但在之前的例子中没有看到Select()方法,因为在Linq方法语法中不需要它,除非在进行投射)
var queryResults = customers.Where(n => n.Region == "North7").Select(c => new {c.City,c.Country,c.ID });
3、投射--单值选择查询(取得不重复的Region值)
(查询语法)
var queryResults=(from n in customers select c.Region).Distinct();
(方法语法)
var queryResults=customers.Select(c=>c.Region).Distinct();