此文章对Linq不会有过多的解释,只用代码呈现Linq的用法!
查看注意事项:
①:命名空间与方法名基本一致,如:All方法的用法,命名空间为All;
②:如:命名空间为GroupBy_02,说明GroupBy方法有多个例子;
③:用例使用了字典排序,方便大家查找!
All用法:
namespace All
{
class Program
{
static void Main(string[] args)
{
AllEx2();
}
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
class Person
{
public string LastName { get; set; }
public Pet[] Pets { get; set; }
}
public static void AllEx2()
{
List<Person> people = new List<Person>
{ new Person { LastName = "Haas",
Pets = new Pet[] { new Pet { Name="Barley", Age=10 },
new Pet { Name="Boots", Age=14 },
new Pet { Name="Whiskers", Age=6 }}},
new Person { LastName = "Fakhouri",
Pets = new Pet[] { new Pet { Name = "Snowball", Age = 1}}},
new Person { LastName = "Antebi",
Pets = new Pet[] { new Pet { Name = "Belle", Age = 8} }},
new Person { LastName = "Philips",
Pets = new Pet[] { new Pet { Name = "Sweetie", Age = 2},
new Pet { Name = "Rover", Age = 13}} }
};
// Determine which people have pets that are all older than 5.
//确定哪些人有5岁以上的宠物:
IEnumerable<string> names = from person in people
where person.Pets.All(pet => pet.Age > 5)
select person.LastName;
foreach (string name in names)
{
Console.WriteLine(name);
}
/* This code produces the following output:
* 此代码输出如下:
* Haas
* Antebi
*/
}
}
}
Any用法:
namespace Any
{
class Program
{
static void Main(string[] args)
{
//Any()方法 确定序列是否包含任何元素。
List<int> numbers = new List<int> { 1, 2 };
bool hasElements = numbers.Any();
Console.WriteLine("The list {0} empty.",
hasElements ? "is not" : "is");
}
}
}
Cast用法:
namespace Cast
{
class Program
{
static void Main(string[] args)
{
ArrayList fruits = new ArrayList();
fruits.Add("mango");
fruits.Add("apple");
fruits.Add("lemon");
IEnumerable<string> query =
fruits.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);
// The following code, without the cast, doesn't compile.下面的代码没有编译,也不会有编译
//IEnumerable<string> query1 =
// fruits.OrderBy(fruit => fruit).Select(fruit => fruit);
foreach (string fruit in query)
{
Console.WriteLine(fruit);
}
// This code produces the following output:
//此代码生成以下输出
// apple
// lemon
// mango
}
}
}
Concat用法:
namespace Concat
{
class Program
{
/// <summary>
/// Concat连接两个字符串
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
ConcatEx1();
}
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
static Pet[] GetCats()
{
Pet[] cats = { new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
return cats;
}
static Pet[] GetDogs()
{
Pet[] dogs = { new Pet { Name="Bounder", Age=3 },
new Pet { Name="Snoopy", Age=14 },
new Pet { Name="Fido", Age=9 } };
return dogs;
}
public static void ConcatEx1()
{
Pet[] cats = GetCats();
Pet[] dogs = GetDogs();
/*下面的代码示例演示如何使用concat <来源>(IEnumerable <来源>,IEnumerable <来源>)连接两个序列。*/
//IEnumerable<string> query =
// cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));
/*另一种方法是将两个序列构建的集合,例如一个数组,序列,
* 然后应用SelectMany方法,通过标识选择器函数。下面的示
* 例演示如何使用SelectMany。*/
IEnumerable<int> query =
new[] { cats.Select(cat => cat.Age), dogs.Select(dog => dog.Age) }
.SelectMany(name => name);
foreach (int name in query)
{
Console.WriteLine(name);
}
}
// This code produces the following output:
//此代码生成以下输出
// Barley
// Boots
// Whiskers
// Bounder
// Snoopy
// Fido
}
}
Contains用法:
namespace Contains
{
class Program
{
/// <summary>
/// 确定序列是否包含指定元素
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string[] fruits = { "apple", "banana", "mango", "orange", "passionfruit", "grape" };
string fruit = "mango";
bool hasMango = fruits.Contains(fruit);
Console.WriteLine(
"The array {0} contain '{1}'.",
hasMango ? "does" : "does not",
fruit);
// This code produces the following output:
//此代码生成以下输出
// The array does contain 'mango'.
}
}
}
namespace Contains_01
{
class Program
{
/// <summary>
/// 下面的示例演示如何实现一个相等比较器可用Contains于方法。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Product[] fruits = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "lemon", Code = 12 } };
Product apple = new Product { Name = "apple", Code = 9 };
Product kiwi = new Product { Name = "kiwi", Code = 8 };
ProductComparer prodc = new ProductComparer();
bool hasApple = fruits.Contains(apple, prodc);
bool hasKiwi = fruits.Contains(kiwi, prodc);
Console.WriteLine("Apple? " + hasApple);
Console.WriteLine("Kiwi? " + hasKiwi);
/*
This code produces the following output:
Apple? True
Kiwi? False
*/
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
// Custom comparer for the Product class
//对Product的自定义比较器
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
//如果Products中的name和Products中Code相等,Products是平等的。
public bool Equals(Product x, Product y)
{
//Check whether the compared objects reference the same data.
//检查比较对象是否引用相同的数据。
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
//检查任何比较对象是否为null。
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
//检查products的属性是否相等
return x.Code == y.Code && x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Product product)
{
//Check whether the object is null
//检查对象是否为null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
//如果 code和name不为空,就获取
int hashProductName = product.Name == null ? 0 : product.Name.GetHashCode();
//Get hash code for the Code field.
//获取Code
int hashProductCode = product.Code.GetHashCode();
//Calculate the hash code for the product.
//计算product的code
return hashProductName ^ hashProductCode;
}
}
}
}
DefaultIfEmpty用法:
namespace DefaultIfEmpty
{
class Program
{
/// <summary>
/// 返回一个IEnumerable <T>的元素,或默认值的单点采集如果序列是空的。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
DefaultIfEmptyEx2();
}
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
/*
下面的代码示例演示如何使用DefaultIfEmpty<TSource>(IEnumerable<TSource>, TSource)方法和指定默认值。
第一个序列不是空的,第二个序列是空的。*/
public static void DefaultIfEmptyEx2()
{
Pet defaultPet = new Pet { Name = "Default Pet", Age = 0 };
List<Pet> pets1 =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
foreach (Pet pet in pets1.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("Name: {0}", pet.Name);
}
List<Pet> pets2 = new List<Pet>();
foreach (Pet pet in pets2.DefaultIfEmpty(defaultPet))
{
Console.WriteLine("Name: {0}", pet.Name);
}
}
/*
This code produces the following output:此代码生成以下输出
Name: Barley
Name: Boots
Name: Whiskers
Name: Default Pet
*/
}
}
namespace DefaultIfEmpty_01
{
class Program
{
static void Main(string[] args)
{
/*这个例子使用了一个非空序列。*/
DefaultIfEmptyEx1();
/*此示例使用空序列。*/
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty())
{
Console.WriteLine(number);
}
/*
This code produces the following output:
0
*/
}
class Pet
{
public string Name { get; set; }
public int Age { get; set; }
}
/*下面的代码示例演示如何使用DefaultIfEmpty<TSource>(IEnumerable<TSource>)提供一个默认值的情况下,源序列是空的。*/
public static void DefaultIfEmptyEx1()
{
List<Pet> pets =
new List<Pet>{ new Pet { Name="Barley", Age=8 },
new Pet { Name="Boots", Age=4 },
new Pet { Name="Whiskers", Age=1 } };
foreach (Pet pet in pets.DefaultIfEmpty())
{
Console.WriteLine(pet.Name);
}
}
/*
This code produces the following output:
Barley
Boots
Whiskers
*/
}
}
Distinct用法:
namespace Distinct
{
class Program
{
/// <summary>
/// Distinct 从序列中返回不同的元素
/// 下面的代码示例演示如何使用Distinct<TSource>(IEnumerable<TSource>)返回一个整数序列不同的元素。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
List<int> ages = new List<int> { 21, 46, 46, 55, 17, 21, 55, 55 };
IEnumerable<int> distinctAges = ages.Distinct();
Console.WriteLine("Distinct ages:");
foreach (int age in distinctAges)
{
Console.WriteLine(age);
}
/*
This code produces the following output:
此代码生成以下输出:
Distinct ages:
21
46
55
17
*/
}
}
}
namespace Distinct_01
{
class Program
{
/// <summary>
/// 如果你想返回从一些自定义数据类型的对象序列不同的元素,
/// 你必须在类中实现iequatable <T>通用接口。
/// 下面的代码示例演示如何在自定义数据类型实现这个接口,
/// 提供GetHashCode和equals方法。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 9 },
new Product { Name = "lemon", Code = 12 } };
//Exclude duplicates.
IEnumerable<Product> noduplicates =
products.Distinct();
foreach (var product in noduplicates)
Console.WriteLine(product.Name + " " + product.Code);
/*
This code produces the following output:
apple 9
orange 4
lemon 12
*/
}
public class Product : IEquatable<Product>
{
public string Name { get; set; }
public int Code { get; set; }
public bool Equals(Product other)
{
//Check whether the compared object is null.
if (Object.ReferenceEquals(other, null)) return false;
//Check whether the compared object references the same data.
if (Object.ReferenceEquals(this, other)) return true;
//Check whether the products' properties are equal.
return Code.Equals(other.Code) && Name.Equals(other.Name);
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public override int GetHashCode()
{
//Get hash code for the Name field if it is not null.
int hashProductName = Name == null ? 0 : Name.GetHashCode();
//Get hash code for the Code field.
int hashProductCode = Code.GetHashCode();
//Calculate the hash code for the product.
return hashProductName ^ hashProductCode;
}
}
}
}
namespace Distinct_02
{
class Program
{
/// <summary>
/// 下面的示例演示如何实现一个相等比较器,可用于Distinct的方法。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
Product[] products = { new Product { Name = "apple", Code = 9 },
new Product { Name = "orange", Code = 4 },
new Product { Name = "apple", Code = 9 },
new Product { Name = "lemon", Code = 12 } };
//Exclude duplicates.
IEnumerable<Product> noduplicates =
products.Distinct(new ProductComparer());
foreach (var product in noduplicates)
Console.WriteLine(product.Name + " " + product.Code);
/*
This code produces the following output:
apple 9
orange 4
lemon 12
*/
}
public class Product
{
public string Name { get; set; }
public int Code { get; set; }
}
// Custom comparer for the Product class
class ProductComparer : IEqualityComparer<Product>
{
// Products are equal if their names and product numbers are equal.
public bool Equals(Product x, Product y)
{
//Check whether the compared objects reference the same data.
if (Object.ReferenceEquals(x, y)) return true;
//Check whether any of the compared objects is null.
if (Object.ReferenceEquals(x, null) || Object.ReferenceEquals(y, null))
return false;
//Check whether the products' properties are equal.
return x.Code == y.Code && x.Name == y.Name;
}
// If Equals() returns true for a pair of objects
// then GetHashCode() must return the same value for these objects.
public int GetHashCode(Product product)
{
//Check whether the object is null
if (Object.ReferenceEquals(product, null)) return 0;
//Get hash code for the Name field if it is not null.
int hashProductName