List Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication7LINQ
{
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()//重写ToString(),默认的ToString()仅输出类型名称
{
return "ID:" + ID + "City:" + City + "Country:" + Country + "Region:" + Region + "Sales:" + Sales;
}
}

class Order
{
public string ID { get; set; }
public decimal Amount { get; set; }
}

class Program
{
/// <summary>
/// 生成随机数组
/// </summary>
/// <param name="count"></param>
/// <returns></returns>
private static int[] GenerateLotsofNumbers(int count)
{
Random generator = new Random(1); //使用指定的种子值初始化 Random 类的新实例。
int[] result = new int[count];
for (int i = 0; i < count; i++)
{
result[i] = generator.Next();
}
return result;
}

//1.用var关键字声明结果变量
//2.指定数据源:from 子句
//3.指定条件:where 子句
//4.指定元素:select子句
//5.完成:使用foreach循环
static void Main(string[] args)
{
// string[] names = { "Alono", "Zheng", "Yuan", "Song", "Simle", "Hsieh", "Small", "She", "Sza", "Sam", "Fa", "Iyl" };
// //var queryResults = from n in names
// // where n.StartsWith("S")
// // orderby n descending//按照最后一个字母排序 ordeby n.Substring(n.Length - 1)
// // select n;//查询语法
// var queryResults = names.OrderBy(n => n).Where(n => n.StartsWith("S"));//方法语法 Lambda 表达式
//// var queryResults = names.OrderByDescending(n => n).Where(n => n.StartsWith("S"));
// foreach (var item in queryResults)
// Console.WriteLine(item);
// Console.ReadKey();

//--------------------------------------------------------------------------------------------------

//int[] numbers = GenerateLotsofNumbers(12345678);
//var queryResults = from n in numbers
// where n < 1000
// select n;
//foreach (var item in queryResults)
//{
// Console.WriteLine(item);
//}
//Console.WriteLine("聚合运算符......");
//Console.WriteLine(queryResults.Count());
//Console.WriteLine(queryResults .Max ());
//Console.WriteLine(queryResults.Average());
//Console.WriteLine(queryResults.Sum());
//Console.ReadKey();

//--------------------------------------------------------------------------------------------------

List<Customer> customers = new List<Customer> {
new Customer {ID ="A",City ="New York",Country ="USA",Region ="North America",Sales =9999},
new Customer {ID ="B",City ="New York",Country ="USA",Region ="North America",Sales =9999},
new Customer {ID ="C",City ="XiAn",Country ="China",Region ="Asia",Sales =7777},
new Customer {ID ="D",City ="New York",Country ="USA",Region ="North America",Sales =9999},
new Customer {ID ="E",City ="BeiJing",Country ="China",Region ="Asia",Sales =8888},
new Customer {ID ="F",City ="New York",Country ="USA",Region ="North America",Sales =9999}
};
//var queryReaults =
// from n in customers
// where n.Region == "Asia"
// select n;
//foreach (var item in queryReaults )
// Console.WriteLine(item);
//Console.ReadKey();

//--------------------------------------投影----------------------------------------------
//投影是在LINQ查询中从其他数据类型中创建新数据类型的术语。
//var queryResults =
// from c in customers
// where c.Region == "Asia"
// select new { c.City, c.Country, c.Sales };
//var queryResults = customers.Where(c => c.Region == "Asia").Select(c => new { c.City, c.Country, c.Sales });
//var queryResults = customers.Select(c => new { c.City, c.Country, c.Sales }).Where(c => c.City == "XiAn");
//foreach (var item in queryResults)
// Console.WriteLine(item);
//Console.ReadKey();

//--------------------单值选择查询------------------------
var queryResults1 = customers.Select(c => c.Region).Distinct();
var queryResults2 = (from c in customers select c.Region).Distinct();

//------------------------Any和All---------------------------------
bool anyUSA = customers.Any(c => c.Country == "USA");
if(anyUSA )
Console.WriteLine("some customers are in USA");
else
Console.WriteLine("WAWA");
bool allAsia = customers.All(c => c.Region == "Asia");
if(allAsia )
Console.WriteLine("WAWA");
else
Console.WriteLine("All customers are in Asia");

// Console.ReadKey();

//--------------------------------多级排序---------------------------------------
var queryReaults3 =
from n in customers
where n.Region == "Asia"
orderby n.Region ,n.Country descending ,n.City //查询语法 多级排序
select n;
var queryResults4 =
customers.OrderBy(c => c.Region).ThenByDescending(c => c.Country).ThenBy(c => c.City).Select(c => new { c.ID, c.Region, c.Country, c.City });
//方法语法 多级排序

//------------------------------------组合查询(group query)-------------------------------------
//组合查询中的数据通过一个键(Key)字段来组合,每一个组中的所有成员都共享这个字段值,在这个例子中 键字段是Region
//要计算每个组的总和,应先生成一个新的结果集cg
var queryResults5 = from c in customers
group c by c.Region into cg
select new { TotalSales = cg.Sum(c => c.Sales), Region = cg.Key };
var orderedResults = from cg in queryResults5
orderby cg.TotalSales descending
select cg;
foreach (var item in orderedResults)
Console.WriteLine(item.TotalSales + "\t:" + item.Region);
//Console.ReadKey();

//------------------------Take 和 Skip----------------------------------
//Take() 从查询结果中提取前n个结果
//Skip() 从查询结果中跳过前n个结果 返回剩余的结果
foreach (var item in orderedResults .Take (2))
Console.WriteLine(item.TotalSales + "\t:" + item.Region);

//---------------------------First 和 FirstOrDefault-------------------------------
//First() 返回结果集中第一个匹配给定条件的元素
//FirstOrDefault() 当查询条件不满足是,将为列表返回默认元素 而使用First()则返回null
Console.WriteLine(queryReaults3.FirstOrDefault(n => n.Region == "Asia"));

//--------------------------------集运算符-----------------------------
List<Order> orders = new List<Order>{
new Order {ID="A",Amount=100},
new Order {ID ="B",Amount =200},
new Order {ID ="H",Amount =300}};

var customersIDs = from c in customers
select c.ID;
var ordersIDs = from o in orders
select o.ID;
var customersWithOrders = customersIDs.Intersect(ordersIDs);//Intersect()
foreach (var item in customersWithOrders )
Console.WriteLine(item );
Console.WriteLine("-------------------------");
var ordersNoCustomers = ordersIDs.Except(customersIDs);//Except()
foreach (var item in ordersNoCustomers )
Console.WriteLine(item );
Console.WriteLine("-------------------------");
var allCustomersOrders = ordersIDs.Union(customersIDs);//Union()
foreach (var item in allCustomersOrders)
Console.WriteLine(item);
//Console.ReadKey();

//---------------------------------Join----------------------------
//使用Join运算符在一个查询中查找多个集合中的相关数据,用键字段把结果连接起来
var queryResults9 =
from c in customers
join o in orders on c.ID equals o.ID
select new { c.ID, c.City, SalesBefore = c.Sales, NewOrder = o.Amount, SalesAfter = c.Sales + o.Amount };
foreach (var item in queryResults9 )
Console.WriteLine(item );
Console.ReadKey();

}
}
}

posted @ 2015-06-05 09:51  KainJC  阅读(254)  评论(0编辑  收藏  举报