[轉貼] Linq初級學習(標準查詢操作符的使用和調用)

2012022813:24

出處:http://www.cnblogs.com/huangcong/archive/2010/12/29/1919817.html

本文章是我最近學習Linq的一些示例,分享給和我一樣剛開始接觸Linq的朋友們作為一個參考,因為是初學,肯定有很多不足,因此希望大家友善提醒,切勿針鋒相對,我會及時改正的~~

目錄

01 投影操作符(Select,SelectMany)

02 限制操作符(Where)

03 排序操作符(OrderBy,OrderByDescending,ThenBy,ThenByDescending,Reverse)

04 聯接操作符(join,GroupJoin)

05 分組操作符(GroupBy)

06 串聯操作符(Concat)

07 聚合操作符(Aggregate,Average,Count,LongCount,Max,Min,Sum)

08 集合操作符(Distinct,Union,Intersect,Except)

09 生成操作符(Empty,Range,Repeat)

10 轉換操作符(Cast,OfType,ToArray,ToDictionary,ToList,ToLookup)

11 元素操作符(DefaultIfEmpty,ElementAt,ElementAtOrDefault,First,Last,FirstOrDefault,LastOrDefault,Single,SingleOrDefault)

12 相等操作符(SequenceEqual)

13 量詞操作符(All,Any)

14 分割操作符(Skip,SkipWhile,Take,TakeWhile)

 

 

 

01.投影操作符(Select,SelectMany)

(1)Select操作符對單個序列或者集合中的值進行投影,可以控制從序列中返回指定的列.

方法語法:

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//創建測試數據
User[] users = new User[]{
new User(){ Id = 1, FirstName = "Huang", LastName = "Cong", Age = 12},
new User(){ Id = 2, FirstName = "Yang", LastName = "Qiu", Age = 22},
new User(){ Id = 3, FirstName = "Cai", LastName = "Zheng", Age = 18},
new User(){ Id = 4, FirstName = "Huang", LastName = "Chao", Age = 32},
new User(){ Id = 5, FirstName = "Teng", LastName = "Jie", Age = 12},
new User(){ Id = 6, FirstName = "Liang", LastName = "Zhi", Age = 8}
};

//使用Select操作符進行投影,對序列只返回First一個列
var query = users.Select(u => new { u.FirstName });

//輸出
foreach (var q in query)
Console.WriteLine(q.FirstName);
}
}

class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }

public override string ToString()
{
return String.Format("Id:{0}\tFirstName:{1}\tLastName:{2}\tAge:{3}", this.Id, this.FirstName, this.LastName, this.Age);
}
}
}
查詢語法:
var query = from u in users select new { u.FirstName };
運行結果:

 

 

 (2)SelectMany操作符提供了將多個from子句組合起來的功能,它將每個對象的結果合併成單個序列.

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//創建測試數據
Names[] owners =
{ new Names { FirstName = "Scott, Chris",
Pets = new List<string>{"Yukon", "Fido"}},
new Names { FirstName = "Jason, Steve",
Pets = new List<string>{"Killer", "Fluffy"}},
new Names { FirstName = "John, Joe",
Pets = new List<string>{"Spike", "Tinkerbell"}}};

//使用SelectMany操作符將每個對象的Pets組合成一個序列
var query = owners.SelectMany(owner => owner.Pets);

//對組合好的Pets進行輸出
foreach (var q in query)
Console.WriteLine(q);
}
}

class Names
{
public string FirstName { get; set; }
public List<string> Pets { get; set; }
}
}

運行結果:

 

02.限制操作符(Where,OfType)

(1)Where是限制操作符,可以對序列中的值進行過濾.Where操作符不啟動查詢的執行.但開始對對像進行迭代的時候才將過濾器應用到數據上.

方法語法:

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//創建測試數據
List<string> names = new List<string>();

names.Add("Scott");
names.Add("Dave");
names.Add("Dave");
names.Add("Steve");
names.Add("Joe");

//使用Where操作符查詢序列中以S開頭的元素
var query = names.Where(n => n.StartsWith("S"));

//對組合好的Pets進行輸出
foreach (var q in query)
Console.WriteLine(q);
}
}
}

查詢語法:

var query = from n in names where n.StartsWith("S") select n;

運行結果:

 

03 排序操作符(OrderBy,OrderByDescending,ThenBy,ThenByDescending,Reverse)

(1)OrderBy/OrderByDescending操作符能將序列中的返回值按照升序/降序的順序進行排列.

方法語法:

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//創建測試數據
List<string> names = new List<string>();

names.Add("Scott");
names.Add("Dave");
names.Add("Dave");
names.Add("Steve");
names.Add("Joe");

//使用OrderBy操作符對序列進行排序
var query = names.Select(n => n).OrderBy(n => n);

Console.WriteLine("----------------------OrderBy排序----------------------");
foreach (var q in query)
Console.WriteLine(q);

//使用OrderByDescending操作符對序列進行倒序
query = names.Select(n => n).OrderByDescending(n => n);

Console.WriteLine("----------------------OrderByDescending排序----------------------");
foreach (var q in query)
Console.WriteLine(q);
}
}
}

查詢語法:

//正序
var query = from n in names orderby n select n;

//倒

query = from n in names orderby n descending select n;

運行結果:

 

(2)ThenBy/ThenByDescending操作符可按照次關鍵對序列進行升序/降序排列.

方法語法:

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { get; set; }
public int Age { get; set; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();

users.Add(new User() { Name = "Scott", Age = 12 });
users.Add(new User() { Name = "Scott", Age = 22 });
users.Add(new User() { Name = "Doe", Age = 11 });
users.Add(new User() { Name = "Doe", Age = 8 });
users.Add(new User() { Name = "Scott", Age = 18 });
users.Add(new User() { Name = "Doe", Age = 24 });

//使用ThenBy操作符對序列再次進行排序
var query = users.Select(u => u).OrderBy(u => u.Name).ThenBy(u => u.Age);

Console.WriteLine("----------------------ThenBy排序----------------------");
foreach (var q in query)
Console.WriteLine("Name:{0}\tAge:{1}", q.Name, q.Age);

//使用ThenByDescending操作符對序列再次進行排序
query = users.Select(u => u).OrderBy(u => u.Name).ThenByDescending(u => u.Age);

Console.WriteLine("----------------------ThenByDescending排序----------------------");
foreach (var q in query)
Console.WriteLine("Name:{0}\tAge:{1}", q.Name, q.Age);
}
}
}

查詢語法:

//正序
var query = from u in users orderby u.Name, u.Age select u;

//倒序
query = (from u in users orderby u.Name select u).ThenByDescending(u => u.Age);

運行結果:

 

(3)Reverse操作符只是簡單的把數據源中的數據按照相反的順序返回.(需要注意的是:Reverse在LINQ To SQL中是不支持的).

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//創建測試數據
List<string> names = new List<string>();

names.Add("Scott");
names.Add("Dave");
names.Add("Dave");
names.Add("Steve");
names.Add("Joe");

//使用Reverse操作符對序列進行逆序排列
names.Reverse();

foreach (var q in names)
Console.WriteLine(q);
}
}
}

運行結果:

 

04 聯接操作符(join,GroupJoin)

(1)join操作符類似於T-SQL中的inner join,它可以將一個數據源與另一個數據源想聯接,根據兩個數據源中相等的值進行匹配.

方法語法:

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { set; get; }
public int RoleId { set; get; }
}

class Role
{
public int Id { get; set; }
public string Name { get; set; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();
List roles = new List ();

roles.Add(new Role() { Id = 1, Name = "Admin" });
roles.Add(new Role() { Id = 2, Name = "Guest" });

users.Add(new User { RoleId = 1, Name = "Scott" });
users.Add(new User { RoleId = 1, Name = "Dave" });
users.Add(new User { RoleId = 2, Name = "Steve" });
users.Add(new User { RoleId = 2, Name = "Joe" });

//查詢出ID為1的角色下的所有用戶
var query = users.Join(roles, u => u.RoleId, r => r.Id, (u, r) => new { UserName = u.Name, RoleId = r.Id, RoleName = r.Name }).Where(q => q.RoleId == 1);

foreach (var q in query)
Console.WriteLine("UserName:{0}\tRoleId:{1}\tRoleName:{2}", q.UserName, q.RoleId, q.RoleName);
}
}
}

查詢語法:

var query = from r in roles
join u in users on r.Id equals u.RoleId
where r.Id == 1
select new { RoleId = r.Id, RoleName = r.Name, UserName = u.Name };

運行結果:

 

(2)GroupJoin操作符類似於T-SQL中的INNER JOIN, LEFT OUTER JOIN,返回的是一個層級的結果集

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { set; get; }
public int RoleId { set; get; }
}

class Role
{
public int Id { get; set; }
public string Name { get; set; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();
List roles = new List ();

roles.Add(new Role() { Id = 1, Name = "Admin" });
roles.Add(new Role() { Id = 2, Name = "Guest" });

users.Add(new User { RoleId = 1, Name = "Scott" });
users.Add(new User { RoleId = 1, Name = "Dave" });
users.Add(new User { RoleId = 2, Name = "Steve" });
users.Add(new User { RoleId = 2, Name = "Joe" });

//查詢所有角色下的用戶
var query = roles.GroupJoin(users, r => r.Id, u => u.RoleId, (role, user) => new { RoleId = role.Id, RoleName = role.Name, Users = user.Where(u => u.RoleId == role.Id) });

foreach (var role in query)
{
Console.WriteLine("RoleId:{0} RoleName:{1}", role.RoleId, role.RoleName);
foreach (var user in role.Users)
{
Console.WriteLine(" "+user.Name);
}
}

}
}
}

運行結果:

 

05 分組操作符(GroupBy)

(1)GroupBy分組操作符是根據一個指定的特定值將序列中的值或元素進行分組.

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { set; get; }
public int RoleId { set; get; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();
users.Add(new User { RoleId = 1, Name = "Scott" });
users.Add(new User { RoleId = 1, Name = "Dave" });
users.Add(new User { RoleId = 2, Name = "Steve" });
users.Add(new User { RoleId = 2, Name = "Joe" });

//按RoleId對所有用戶進行分組
var query = users.GroupBy(u => u.RoleId);

foreach (var o in query)
{
Console.WriteLine("RoleId:{0}:", o.Key);
foreach (var user in o)
{
Console.WriteLine(" Name:{0}", user.Name);
}
}
}
}
}

運行結果:

 

06 串聯操作符(Concat)

(1)Concat操作符可以將兩個對像聯接在一起

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { set; get; }
public int RoleId { set; get; }
}

class Role
{
public int Id { get; set; }
public string Name { get; set; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();
List roles = new List ();

roles.Add(new Role() { Id = 1, Name = "Admin" });
roles.Add(new Role() { Id = 2, Name = "Guest" });

users.Add(new User { RoleId = 1, Name = "Scott" });
users.Add(new User { RoleId = 1, Name = "Dave" });
users.Add(new User { RoleId = 2, Name = "Steve" });
users.Add(new User { RoleId = 2, Name = "Joe" });

//按所有的用戶名稱和角色名稱聯接起來
var query = users.Select(u => u.Name).Concat(roles.Select(r => r.Name));

foreach (var q in query)
{
Console.WriteLine(q);
}
}
}
}

運行結果:

 

07 聚合操作符(Aggregate,Average,Count,LongCount,Max,Min,Sum)

(1)聚合函數是在序列上執行特定的運算後返回單個值.共有7個聚合查詢操作符:
  Aggregate:將序列中的值進行累積並返回結果.
    Average:計算一個數值序列的平均值.
    Count,LongCount:計算一個集合中元素的個數.但是前者返回的是Int32類型的值,後者為Int64
    Max,Min:分別是返回序列中的最大值和最小值
    Sum:返回集合中數值的總和

代碼
//-----------------------------------------------------------
// All Rights Reserved , Copyright (C) 2010 ,黃聰 , Ltd .
//-----------------------------------------------------------

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

namespace ConsoleApplication1
{
class Program
{
class User
{
public string Name { set; get; }
public int Age { set; get; }
}

static void Main(string[] args)
{
//創建測試數據
List users = new List ();

users.Add(new User { Age = 12, Name = "Scott" });
users.Add(new User { Age = 22, Name = "Dave" });
users.Add(new User { Age = 18, Name = "Steve" });
users.Add(new User { Age = 24, Name = "Joe" });

string Names = "Scott,Dave,Steve,Joe";
string[] name = Names.Split(',');
Console.WriteLine("使用Aggregate將名稱組合起來:");
string query1 = name.Aggregate((n, next) => n + " " + next);
Console.WriteLine(query1);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用Average求出所有用戶年齡的平均數:");
var query2 = users.Select(u => u.Age).Average();
Console.WriteLine(query2);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用Count求出總共有多少個用戶:");
var query3 = users.Count();
Console.WriteLine(query3);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用LongCount求出所有用戶年齡的平均數:");
var query4 = users.LongCount();
Console.WriteLine(query4);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用Max求出所有用戶年齡的最大數:");
var query5 = users.Select(u => u.Age).Max();
Console.WriteLine(query5);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用Min求出所有用戶年齡的最小數:");
var query6 = users.Select(u => u.Age).Min();
Console.WriteLine(query6);
Console.WriteLine("------------------------------------------------");

Console.WriteLine("使用Sum求出所有用戶年齡的總和:");
var query7 = users.Select(u => u.Age).Sum();
Console.WriteLine(query7);
Console.WriteLine("------------------------------------------------");
}
}
}

運行結果:

 

08 集合操作符(Distinct,Union,Intersect,Except)

(1)Distinct操作符可以刪除集合中重複的值,並返回該集合中不相同的元素.

代碼
//-----------------------------------------------------------
// All Ri