于梦想齐行
于梦想齐行

Enumerable Class (C#)

Enumerable Class (C#)

提供一组静态方法用于查询实现IEnumerable<T>的对象。

Methods

1.Aggregate

在序列上应用累加器函数。指定的值作为初始累加器值,指定的函数用于选择结果。

List<String> fruits = new List<string>();
fruits.AddRange(new string[] { "apple", "mango", "orange", "passionfruit"});
string longestName = fruits.Aggregate("banana", (longest, next) => next.Length > longest.Length ? next : longest, fruit => fruit.ToUpper());
Console.WriteLine("the fruit with longest name is {0}.", longestName);
//the fruit with longest name is PASSIONFRUIT.

2.All

判断序列的所有值是否都满足特定条件。

public class Pet {
  public string Name {
    get;
    set;
  }
  public int Age {
    get;
    set;
  }
}

public class Person {
  public string LastName {
    get;
    set;
  }
  public Pet[] Pets {
    get;
    set;
  }
}
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},
                                     }}};
//筛选所有宠物年龄大于5的所有人
IEnumerable<string> allownpetgt5names =
    from person in people where
        person.Pets.All(pet => pet.Age > 5) select person.LastName;
foreach (string name in allownpetgt5names) {
  Console.WriteLine(name);
}
// All
Console.WriteLine("all pet`s age >5: {0}",
                  people[0].Pets.All(i => i.Age > 5));  // True

3.Any

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},
                                     }}};
//筛选所有宠物年龄大于5的所有人
IEnumerable<string> allownpetgt5names =
    from person in people where
        person.Pets.All(pet => pet.Age > 5) select person.LastName;
foreach (string name in allownpetgt5names) {
  Console.WriteLine(name);
}
// Any
Console.WriteLine("any pet`s age >5: {0}",
                  people[3].Pets.Any(i => i.Age > 5));  // True

4.Append

List<int> numbers = new List<int>{1, 2, 3, 4};
numbers.Append(5);
Console.WriteLine(string.Join(",", numbers));            // 1,2,3,4
Console.WriteLine(string.Join(",", numbers.Append(5)));  // 1,2,3,4,5
List<int> newNumbers = numbers.Append(5).ToList();
Console.WriteLine(string.Join(",", newNumbers));  // 1,2,3,4,5

5.AsEnumerable

class Clump<T> : List<T> {
  public IEnumerable<T> Where(Func<T, bool> predicate) {
    Console.WriteLine("In Clump`s implmentation of Where().");
    return Enumerable.Where(this, predicate);
  }
}
Clump<string> fruitClump =
    new Clump<string>{"apple",  "passionfruit", "banana", "mongo",
                      "orange", "blueberry",    "grape",  "strawberry"};
// first: call clump`s Where() method with a predicate
IEnumerable<string> query1 = fruitClump.Where(fruit => fruit.Contains("o"));
// second: first call AsEnumerable() to hide Clump`s Where() method and thereby
// force System.Linq.Enumerable`s Where() method to be called.
IEnumerable<string> query2 =
    fruitClump.AsEnumerable().Where(fruit => fruit.Contains("o"));

6.Average

long ? [] longs = {null, 10007L, 37L, 399846234235L};
double ? average = longs.Average();
Console.WriteLine("The average is {0}.", average);

7.Cast

System.Collections.ArrayList fruits2 = new System.Collections.ArrayList();
fruits2.Add("mongo");
fruits2.Add("apple");
fruits2.Add("lemon");
IEnumerable<string> query =
    fruits2.Cast<string>().OrderBy(fruit => fruit).Select(fruit => fruit);
//下面的代码没有cast无法编译通过
// IEnumerable<string> query = fruits2.OrderBy(fruit => fruit).Select(fruit =>
// fruit);
foreach (string fruit in query) {
  Console.WriteLine(fruit);
}

8.Chunk 分块和分块并行

var list = Enumerable.Range(1, 100);  // 1-100
var chunkSize = 10;
foreach (var chunk in list.Chunk(
             chunkSize))  // 1-10,11-20,21-30,31-40,41-50,51-60...91-100
{
  Console.WriteLine("=>");
  foreach (var item in chunk) {
    Console.WriteLine(item);
  }
}
foreach (var chunk in list.Chunk(
             chunkSize))  // 1-10,11-20,21-30,31-40,41-50,51-60...91-100
{
  Console.WriteLine("=>");
  Parallel.ForEach(chunk, (item) => { Console.WriteLine(item); });
}

9.Concat

static Pet[] GetCats() {
  Pet[] pets = {
      new Pet{Name = "Barley", Age = 8},
      new Pet{Name = "Boots", Age = 4},
      new Pet{Name = "Whiskers", Age = 1},
  };
  return pets;
}

static Pet[] GetDogs() {
  Pet[] pets = {
      new Pet{Name = "Bounder", Age = 3},
      new Pet{Name = "Snoopy", Age = 14},
      new Pet{Name = "Fido", Age = 9},
  };
  return pets;
}
Pet[] cats = GetCats();
Pet[] dogs = GetDogs();
IEnumerable<string> query =
    cats.Select(cat => cat.Name).Concat(dogs.Select(dog => dog.Name));
foreach (string name in query) {
  Console.WriteLine(name);
}

10.Contains

long[] ls = new long[]{1L, 2L, 5L, 7L};
Console.WriteLine("is contains 5L: {0}", ls.Contains(5L));
Console.WriteLine("is contains 5L: {0}", Enumerable.Contains(ls, 5L));

11.Count

long[] ls = new long[]{1, 2, 3, 4, 5, 6};
Console.WriteLine("count: {0}", ls.Count());
Console.WriteLine("count: {0}", Enumerable.Count(ls));

12.DefaultIfEmpty

// non-empty sequence
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);  // Barley Boots Whiskers
}
// empty sequence
List<int> numbers = new List<int>();
foreach (int number in numbers.DefaultIfEmpty()) {
  Console.WriteLine(number);  // 0
}

13.Distinct 通过Comparer去重

Product[] products = new Product[]{new Product{Name = "apple", Code = 8},
                                   new Product{Name = "apple", Code = 9},
                                   new Product{Name = "orange", Code = 4},
                                   new Product{Name = "apple", Code = 9},
                                   new Product{Name = "lemon", Code = 12}};
foreach (Product product in products)
  Console.WriteLine("name: {0}, code: {1}", product.Name, product.Code);
/*
 *  name: apple, code: 8
    name: apple, code: 9
    name: orange, code: 4
    name: apple, code: 9
    name: lemon, code: 12
 */
IEnumerable<Product> noduplicates = products.Distinct(new ProductComparer());
foreach (Product product in noduplicates)
  Console.WriteLine("name: {0}, code: {1}", product.Name, product.Code);
/*
 *  name: apple, code: 8
    name: apple, code: 9
    name: orange, code: 4
    name: lemon, code: 12
*/
class ProductComparer : IEqualityComparer<Product> {
  // Products are equal if their names and product number 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([ DisallowNull ] Product obj) {
    // Check wheather the object is null
    if (Object.ReferenceEquals(obj, null)) return 0;
    // Get hash code for the Name field if it is not null
    int hashProductName = obj.Name == null ? 0 : obj.Name.GetHashCode();
    // Get hash code for the Code field
    int hashProductCode = obj.Code.GetHashCode();
    // Calculate the hash code for the product.
    return hashProductName ^ hashProductCode;
  }
}

14.DistinctBy 通过func去重

Product[] collectionWithDuplicates = new Product[]{
    new Product{Name = "good", Code = 9}, new Product{Name = "apple", Code = 9},
    new Product{Name = "orange", Code = 4},
    new Product{Name = "apple", Code = 9},
    new Product{Name = "lemon", Code = 12}};
var uniqueCollection =
    collectionWithDuplicates.DistinctBy(x => x.Name).ToList();
foreach (Product product in uniqueCollection)
  Console.WriteLine("name: {0}, code: {1}", product.Name, product.Code);
/*
 *  name: good, code: 9
 *  name: orange, code: 5
    name: apple, code: 9
    name: lemon, code: 12
 */

15.ElementAt

int[] ints = new int[]{
    1, 2, 3, 4, 5,
};
Console.WriteLine(ints.ElementAt(3));  // 4

16.ElementAtOrDefault

int[] ints = new int[]{
    1, 2, 3, 4, 5,
};
Console.WriteLine(ints.ElementAtOrDefault(5));  // 0

17.Empty 返回指定类型的空序列

IEnumerable<decimal> empty = Enumerable.Empty<decimal>();

18.Except 产生两个序列的集合差

int[] ints1 = new int[]{
    1, 2, 3, 4, 5,
};
int[] ints2 = new int[]{
    1, 2, 0, 3, 6,
};
Console.WriteLine(JsonConvert.SerializeObject(
    Enumerable.Except(ints1, ints2)));  //[4,5] ints1中排除ints2

19.ExceptBy

Product[] products1 = new Product[]{new Product{Name = "blueberry", Code = 9},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "orange", Code = 4},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "lemon", Code = 12}};
Product[] products2 = new Product[]{new Product{Name = "mongo", Code = 9},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "orange", Code = 4},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "lemon", Code = 12}};
// Enumerable.ExceptBy(products1, products2, ProductNameSelector);
foreach (Product product in products1.ExceptBy(
             products2.Select(ProductNameSelector),
             ProductNameSelector))  // products.ExceptBy(names, NameSelector)
{
  Console.WriteLine("name: {0}, code: {1}", product.Name,
                    product.Code);  // name: blueberry, code: 9
}
static string ProductNameSelector(Product product) => product.Name;

20.First

int[] ints1 = new int[]{
    1, 2, 3, 4, 5,
};
Console.WriteLine("first: {0}", ints1.First());  // 1

21.FirstOrDefault

int[] ints1 = new int[]{};
Console.WriteLine("first: {0}", ints1.FirstOrDefault());  // 0

22.GroupBy

// Create a list of pets.
List<Pet2> petsList = new List<Pet2>{new Pet2{Name = "Barley", Age = 8.3},
                                     new Pet2{Name = "Boots", Age = 4.9},
                                     new Pet2{Name = "Whiskers", Age = 1.5},
                                     new Pet2{Name = "Daisy", Age = 4.3}};

// Group Pet.Age values by the Math.Floor of the age.
// Then project an anonymous type from each group
// that consists of the key, the count of the group's
// elements, and the minimum and maximum age in the group.
var query = petsList.GroupBy(
    pet => Math.Floor(pet.Age),  //@1
    pet => pet.Age,
    (baseAge, ages) =>
        new {Key = baseAge,  //@1
             Count = ages.Count(), Min = ages.Min(), Max = ages.Max()});
Console.WriteLine(JsonConvert.SerializeObject(query));

// Iterate over each anonymous type.
foreach (var result in query) {
  Console.WriteLine("\nAge group: " + result.Key);
  Console.WriteLine("Number of pets in this age group: " + result.Count);
  Console.WriteLine("Minimum age: " + result.Min);
  Console.WriteLine("Maximum age: " + result.Max);
}

/*  This code produces the following output:

    Age group: 8
    Number of pets in this age group: 1
    Minimum age: 8.3
    Maximum age: 8.3

    Age group: 4
    Number of pets in this age group: 2
    Minimum age: 4.3
    Maximum age: 4.9

    Age group: 1
    Number of pets in this age group: 1
    Minimum age: 1.5
    Maximum age: 1.5
*/

23.IntersectBy

int[] ints1 = new int[]{
    1, 2, 3, 4, 5,
};
int[] ints2 = new int[]{
    1, 2, 0, 3, 6,
};
Console.WriteLine(
    JsonConvert.SerializeObject(Enumerable.Intersect(ints1, ints2)));  //[1,2,3]
Product[] products1 = new Product[]{new Product{Name = "blueberry", Code = 9},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "orange", Code = 4},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "lemon", Code = 12}};
Product[] products2 = new Product[]{new Product{Name = "mongo", Code = 9},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "orange", Code = 4},
                                    new Product{Name = "apple", Code = 9},
                                    new Product{Name = "lemon", Code = 12}};
Console.WriteLine(JsonConvert.SerializeObject(
    Enumerable.Intersect(products1, products2, new ProductComparer())));
//[{"Name":"apple","Code":9},{"Name":"orange","Code":4},{"Name":"lemon","Code":12}]

24.Join

Person3 magnus = new Person3{Name = "Hedlund, Magnus"};
Person3 terry = new Person3{Name = "Adams, Terry"};
Person3 charlotte = new Person3{Name = "Weiss, Charlotte"};

Pet3 barley = new Pet3{Name = "Barley", Owner = terry};
Pet3 boots = new Pet3{Name = "Boots", Owner = terry};
Pet3 whiskers = new Pet3{Name = "Whiskers", Owner = charlotte};
Pet3 daisy = new Pet3{Name = "Daisy", Owner = magnus};

List<Person3> people3 = new List<Person3>{magnus, terry, charlotte};
List<Pet3> pets3 = new List<Pet3>{barley, boots, whiskers, daisy};

// create a list of person-pet pairs where
// each element is an anonymous type that contains a
// pet`s name and the name of the person that owns the pet
// Join<TOuter,TInner,TKey,TResult>(IEnumerable<TOuter>, IEnumerable<TInner>,
// Func<TOuter,TKey>, Func<TInner,TKey>, Func<TOuter,TInner,TResult>)
var query = people3.Join(
    pets3, person => person, pet => pet.Owner,
    (person, pet) => new {OwnerName = person.Name, Pet = pet.Name});
foreach (var obj in query) {
  Console.WriteLine("{0} - {1}", obj.OwnerName, obj.Pet);
}

25.Last

var a = new string[] { "123", "123", "123", "333" };
Console.WriteLine(a.Last());//333

26.LastOrDefault

var a = new string[] {  };
Console.WriteLine(a.LastOrDefault());// 

27.LongCount

Pet[] pets = {
new Pet{Name = “Barley”, Age = 8},
new Pet{Name = “Boots”, Age = 4},
new Pet{Name = “Whiskers”, Age = 1},
};
const int Age = 3;
long count = pets.LongCount(pet => pet.Age > Age);
Console.WriteLine(“There are {0} animals over age {1}.”, count, Age);

28.Max

var a = new int[] { 1, 3, 2 };
Console.WriteLine("the max: {0}", a.Max());

29.MaxBy

Pet[] pets = {
    new Pet{Name = "Barley", Age = 8},
    new Pet{Name = "Boots", Age = 4},
    new Pet{Name = "Whiskers", Age = 1},
};
Console.WriteLine("the max: {0}",
                  JsonConvert.SerializeObject(pets.MaxBy(pet => pet.Age)));
Console.WriteLine("the max: {0}",
                  JsonConvert.SerializeObject(pets.MaxBy(pet => pet,
                                                         new MyPetComparer())));
public class MyPetComparer : IComparer<Pet> {
  int IComparer<Pet>.Compare(Pet? x, Pet? y) { return x.Age - y.Age; }
}

30.Min

var a = new int[] { 1, 3, 2 };
Console.WriteLine("the min: {0}", a.Min());

31.MinBy

Pet[] pets = {
    new Pet{Name = "Barley", Age = 8},
    new Pet{Name = "Boots", Age = 4},
    new Pet{Name = "Whiskers", Age = 1},
};
Console.WriteLine("the min: {0}",
                  JsonConvert.SerializeObject(pets.MinBy(pet => pet.Age)));
Console.WriteLine("the min: {0}",
                  JsonConvert.SerializeObject(pets.MinBy(pet => pet,
                                                         new MyPetComparer())));
public class MyPetComparer : IComparer<Pet> {
  int IComparer<Pet>.Compare(Pet? x, Pet? y) { return x.Age - y.Age; }
}

32.OfType

ArrayList mixedList = new ArrayList();
mixedList.Add(0);
mixedList.Add("Gnanavel Sekar");
mixedList.Add("Two");
mixedList.Add(3);
mixedList.Add(3.21f);
mixedList.Add(new Pet{Name = "Whiskers", Age = 1});
var stringResult = from s in mixedList.OfType<string>() select s;
foreach (var item in stringResult) {
  Console.WriteLine(item);
}
/*
 * Gnanavel Sekar
 * Two
 */
var intResult = from s in mixedList.OfType<int>() select s;
foreach (var item in intResult) {
  Console.WriteLine(item);
}
/*
 * 0
 * 3
 */

33.OrderBy 升序

Pet[] pets = {
    new Pet{Name = "Barley", Age = 8},
    new Pet{Name = "Boots", Age = 4},
    new Pet{Name = "Whiskers", Age = 1},
};
Console.WriteLine(JsonConvert.SerializeObject(pets.OrderBy(pet => pet.Age)));
Console.WriteLine(
    JsonConvert.SerializeObject(pets.OrderBy(pet => pet, new MyPetComparer())));
public class MyPetComparer : IComparer<Pet> {
  int IComparer<Pet>.Compare(Pet? x, Pet? y) { return x.Age - y.Age; }
}

34.OrderByDescending 降序

Pet[] pets = {
    new Pet{Name = "Barley", Age = 8},
    new Pet{Name = "Boots", Age = 4},
    new Pet{Name = "Whiskers", Age = 1},
};
Console.WriteLine(
    JsonConvert.SerializeObject(pets.OrderByDescending(pet => pet.Age)));
Console.WriteLine(JsonConvert.SerializeObject(
    pets.OrderByDescending(pet => pet, new MyPetComparer())));
public class MyPetComparer : IComparer<Pet> {
  int IComparer<Pet>.Compare(Pet? x, Pet? y) { return x.Age - y.Age; }
}

35.Prepend 向前追加

List<int> numbers = new List<int>{1, 2, 3, 4};
numbers.Prepend(0);
Console.WriteLine(JsonConvert.SerializeObject(numbers));             // 1,2,3,4
Console.WriteLine(JsonConvert.SerializeObject(numbers.Prepend(0)));  // 0,1,2,3,4
List<int> newNumbers = numbers.Prepend(0).ToList();
Console.WriteLine(JsonConvert.SerializeObject(newNumbers));  // 0,1,2,3,4

36.Range

IEnumerable<int> squares = Enumerable.Range(1, 10).Select(x => x * x);
foreach (int num in squares) {
  Console.WriteLine(num);
}

37.Repeat 生成多个相同重复值的序列

IEnumerable<string> strs = Enumerable.Repeat("I like programming.", 15);
foreach (String str in strs) {
  Console.WriteLine(str);
}

38.Reverse

List<int> numbers = new List<int>{1, 2, 3, 4};
numbers.Reverse();
Console.WriteLine(JsonConvert.SerializeObject(numbers));  // 4,3,2,1

39.Select

string[] fruits3 = {"apple",  "banana",       "mango",
                    "orange", "passionfruit", "grape"};
var query = fruits3.Select((fruit, index) =>
                               new {index, str = fruit.Substring(0, index)});
foreach (var obj in query) {
  Console.WriteLine("{0}", obj);
}

40.SelectMany

PetOwner[] petOwners = new PetOwner[]{
    new PetOwner{Name = "Higa", Pets = new List<string>{"Scruffy", "Sam"}},
    new PetOwner{Name = "Ashkenazi",
                 Pets = new List<string>{"Walker", "Sugar"}},
    new PetOwner{Name = "Price",
                 Pets = new List<string>{"Scratches", "Diesel"}},
    new PetOwner{Name = "Hines", Pets = new List<string>{"Dusty"}},
};
var query1 = petOwners.SelectMany(
    petOwner => petOwner.Pets,
    (petOwner, petName) => new {petOwner, petName});  //将petOwner.Pets展开
Console.WriteLine(JsonConvert.SerializeObject(query1));
/*
 * [
 * {"petOwner":{"Name":"Higa","Pets":["Scruffy","Sam"]},"petName":"Scruffy"},
 * {"petOwner":{"Name":"Higa","Pets":["Scruffy","Sam"]},"petName":"Sam"},
 * {"petOwner":{"Name":"Ashkenazi","Pets":["Walker","Sugar"]},"petName":"Walker"},
 * {"petOwner":{"Name":"Ashkenazi","Pets":["Walker","Sugar"]},"petName":"Sugar"},
 * {"petOwner":{"Name":"Price","Pets":["Scratches","Diesel"]},"petName":"Scratches"},
 * {"petOwner":{"Name":"Price","Pets":["Scratches","Diesel"]},"petName":"Diesel"},
 * {"petOwner":{"Name":"Hines","Pets":["Dusty"]},"petName":"Dusty"}
 * ]
 */
// project the pet owner`s name and the pet`s name
var query = petOwners
                .SelectMany(petOwner => petOwner.Pets,
                            (petOwner, petName) => new {petOwner, petName})
                .Where(ownerAndPet => ownerAndPet.petName.StartsWith("S"))
                .Select(ownerAndPet => new {Owner = ownerAndPet.petOwner.Name,
                                            Pet = ownerAndPet.petName});
foreach (var obj in query) {
  Console.WriteLine(obj);
}

41.SequenceEqual

Pet pet1 = new Pet{Name = "Turbo", Age = 2};
Pet pet2 = new Pet{Name = "Peanut", Age = 9};

List<Pet> pets1 = new List<Pet>{pet1, pet2};
List<Pet> pets2 = new List<Pet>{pet1, pet2};

bool equal = pets1.SequenceEqual(pets2);
Console.WriteLine("The sequence is equals: {0}.", equal);  // True

List<Pet> pets3 = new List<Pet>{pet1, pet2};
List<Pet> pets4 = new List<Pet>{
    new Pet{Name = "Turbo", Age = 2},
    new Pet{Name = "Peanut", Age = 9},
};
bool equal2 = pets3.SequenceEqual(pets4);
Console.WriteLine("The sequence is equals: {0}.", equal2);  // False
//在这里比较的是引用地址

//可以自行实现IEquatable接口,重写GetHashCode和Equals方法
List<ProductA> pets5 = new List<ProductA>{
    new ProductA{Name = "Turbo", Code = 2},
    new ProductA{Name = "Peanut", Code = 9},
};
List<ProductA> pets6 = new List<ProductA>{
    new ProductA{Name = "Turbo", Code = 2},
    new ProductA{Name = "Peanut", Code = 9},
};
bool equal3 = pets5.SequenceEqual(pets6);
Console.WriteLine("The sequence is equals: {0}.", equal3);  // True

Console.WriteLine(JsonConvert.SerializeObject((9, 9)));  //{"Item1":9,"Item2":9}
public class ProductA : IEquatable<ProductA> {
  public string Name {
    get;
    set;
  }
  public int Code {
    get;
    set;
  }

  public bool Equals(ProductA other) {
    if (other is null) return false;

    return this.Name == other.Name && this.Code == other.Code;
  }

  public override bool Equals(object obj) => Equals(obj as ProductA);
  public override int GetHashCode() =>(Name, Code).GetHashCode();
}

42.Single 返回一条匹配结果

string[] fruits3 = {"apple",  "banana",       "mango",
                    "orange", "passionfruit", "grape"};
string fruit1 = null;
try {
  fruit1 = fruits3.Single(fruit => fruit.Length > 20);
} catch (System.InvalidOperationException) {
  Console.WriteLine(
      @"The collection does not contain exactly one element whose length is grater than 20.");
}
Console.WriteLine(fruit1);

43.SingleOrDefault

string[] fruits3 = {"apple",  "banana",       "mango",
                    "orange", "passionfruit", "grape"};
string fruit1 = fruits3.SingleOrDefault(fruit => fruit.Length > 20);
Console.WriteLine(fruit1);

44.Skip 从序号0开始跳过指定个

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades = grades.OrderByDescending(g => g).Skip(3);
Console.WriteLine("All grades except the top three are:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
} /*
   * All grades except the top three are:
   82
   70
   59
   56
   */

45.SkipLast 从末尾倒数跳过指定个

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades = grades.OrderByDescending(g => g).SkipLast(3);
Console.WriteLine("All grades except the last three are:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
} /*
   *98
  92
  85
  82
   */

46.SkipWhile 按特定条件

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades =
    grades.OrderByDescending(g => g).SkipWhile(g => g >= 80);
Console.WriteLine("All grades below 80:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
} /*
   *All grades below 80:
   *70
   *59
   *56
   */

47.Sum 求和

int[] grades = { 59, 82, 70, 56, 92, 98, 85 };
Console.WriteLine("sum: {0}", grades.Sum());//sum: 542

48.Take 从序号0开始选择指定个

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades = grades.OrderByDescending(g => g).Take(3);
Console.WriteLine("the top threee grades are:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
} /*
   98
   92
   85
   */

49.TakeLast 从末尾开始倒数选择指定个

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades = grades.OrderByDescending(g => g).TakeLast(3);
Console.WriteLine("the last three grades are:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
}

50.TakeWhile 按特定条件选择

int[] grades = {59, 82, 70, 56, 92, 98, 85};
IEnumerable<int> lowerGrades =
    grades.OrderByDescending(g => g).TakeWhile(g => g >= 80);
Console.WriteLine("All grades grater than 80:");
foreach (int grade in lowerGrades) {
  Console.WriteLine(grade);
}

51.ThenBy 后续排序,用于OrderBy后

string[] fruits3 = {"grape",  "passionfruit", "banana", "mango",
                    "orange", "raspberry",    "apple",  "blueberry"};

// Sort the strings first by their length and then
// alphabetically by passing the identity selector function.
IEnumerable<string> query =
    fruits3.OrderBy(fruit => fruit.Length).ThenBy(fruit => fruit);

foreach (string fruit in query) {
  Console.WriteLine(fruit);
}
/*
 * apple
 * grape
 * mango
 * banana
 * orange
 * blueberry
 * raspberry
 * passionfruit
 */
//当没有使用ThenBy时,注意观察字符长度一致的排序
/* grape
 * mango
 * apple
 * banana
 * orange
 * raspberry
 * blueberry
 * passionfruit
 */

52.ThenByDescending 后续排序倒序

string[] fruits3 = {"apPLe",  "baNanA", "apple",  "APple",
                    "orange", "BAnana", "ORANGE", "apPLE"};

// Sort the strings first ascending by their length and
// then descending using a custom case insensitive comparer.
IEnumerable<string> query =
    fruits3.OrderBy(fruit => fruit.Length)
        .ThenByDescending(fruit => fruit, new CaseInsensitiveComparer());
foreach (string fruit in query) {
  Console.WriteLine(fruit);
}
//无ThenByDescending时,注意观察长度一致的单词排序
/*
 * apPLe
 * apple
 * APple
 * apPLE
 * baNanA
 * orange
 * BAnana
 * ORANGE
 */
//有ThenByDescending时,注意观察长度一致的单词排序
/*
 * apPLe
 * apple
 * APple
 * apPLE
 * orange
 * ORANGE
 * baNanA
 * BAnana
 */

53.ToArray

List<Package> packages = new List<Package>{
    new Package{Company = "Coho Vineyard", Weight = 25.2},
    new Package{Company = "Lucerne Publishing", Weight = 18.7},
    new Package{Company = "Wingtip Toys", Weight = 6.0},
    new Package{Company = "Adventure Works", Weight = 33.8}};

string[] companies = packages.Select(pkg => pkg.Company).ToArray();

foreach (string company in companies) {
  Console.WriteLine(company);
}
/*
 *Coho Vineyard
 *Lucerne Publishing
 *Wingtip Toys
 *Adventure Works
 */

54.ToDirectory

List<Package> packages =
    new List<Package>{new Package{Company = "Coho Vineyard", Weight = 25.2,
                                    TrackingNumber = 89453312L},
                       new Package{Company = "Lucerne Publishing",
                                    Weight = 18.7, TrackingNumber = 89112755L},
                       new Package{Company = "Wingtip Toys", Weight = 6.0,
                                    TrackingNumber = 299456122L},
                       new Package{Company = "Adventure Works", Weight = 33.8,
                                    TrackingNumber = 4665518773L}};

// Create a Dictionary of Package objects,
// using TrackingNumber as the key.
Dictionary<long, Package> dictionary =
    packages.ToDictionary(p => p.TrackingNumber);

foreach (KeyValuePair<long, Package> kvp in dictionary) {
  Console.WriteLine("Key {0}: {1}, {2} pounds", kvp.Key, kvp.Value.Company,
                    kvp.Value.Weight);
}
class Package {
  public string Company {
    get;
    set;
  }
  public double Weight {
    get;
    set;
  }
  public long TrackingNumber {
    get;
    set;
  }
}

55.ToHashSet

public class ProductA : IEquatable<ProductA> {
  public string Name {
    get;
    set;
  }
  public int Code {
    get;
    set;
  }

  public bool Equals(ProductA other) {
    if (other is null) return false;

    return this.Name == other.Name && this.Code == other.Code;
  }

  public override bool Equals(object obj) => Equals(obj as ProductA);
  public override int GetHashCode() =>(Name, Code).GetHashCode();
}
public class ProductB {
  public string Name {
    get;
    set;
  }
  public int Code {
    get;
    set;
  }
}
int[] a = new int[]{1, 2, 3, 4, 5, 4, 3, 2, 1};
Console.WriteLine(JsonConvert.SerializeObject(a.ToHashSet()));  //[1,2,3,4,5]
List<ProductA> pets5 = new List<ProductA>{
    new ProductA{Name = "Peanut", Code = 9},
    new ProductA{Name = "Turbo", Code = 2},
    new ProductA{Name = "Peanut", Code = 9},
};
Console.WriteLine(JsonConvert.SerializeObject(
    pets5
        .ToHashSet()));  //[{"Name":"Peanut","Code":9},{"Name":"Turbo","Code":2}]
List<ProductB> pets6 = new List<ProductA2>{
    new ProductB{Name = "Peanut", Code = 9},
    new ProductB{Name = "Turbo", Code = 2},
    new ProductB{Name = "Peanut", Code = 9},
};
Console.WriteLine(JsonConvert.SerializeObject(pets6.ToHashSet(
    new ProductBComparer())));  //[{"Name":"Peanut","Code":9},{"Name":"Turbo","Code":2}]
public class ProductBComparer : IEqualityComparer<Product> {
  bool IEqualityComparer<ProductB>.Equals(ProductB? x, ProductB? y) {
    if (x is null || y is null) return false;

    return x.Name == y.Name && x.Code == y.Code;
  }

  int IEqualityComparer<ProductB>.GetHashCode(ProductB obj) {
    return (obj.Name, obj.Code).GetHashCode();
  }
}

56.ToList

int[] a = new int[]{1, 2, 3, 4, 5, 4, 3, 2, 1};
Console.WriteLine(
    JsonConvert.SerializeObject(a.ToList()));  //[1,2,3,4,5,4,3,2,1]

57.ToLookup 分组

class PackageB {
  public string Company {
    get;
    set;
  }
  public double Weight {
    get;
    set;
  }
  public long TrackingNumber {
    get;
    set;
  }
}
// Create a list of Packages.
List<PackageB> packages = new List<PackageB>{
    new PackageB{Company = "Coho Vineyard", Weight = 25.2,
                 TrackingNumber = 89453312L},
    new PackageB{Company = "Lucerne Publishing", Weight = 18.7,
                 TrackingNumber = 89112755L},
    new PackageB{Company = "Wingtip Toys", Weight = 6.0,
                 TrackingNumber = 299456122L},
    new PackageB{Company = "Contoso Pharmaceuticals", Weight = 9.3,
                 TrackingNumber = 670053128L},
    new PackageB{Company = "Wide World Importers", Weight = 33.8,
                 TrackingNumber = 4665518773L}};

// Create a Lookup to organize the packages.
// Use the first character of Company as the key value.
// Select Company appended to TrackingNumber
// as the element values of the Lookup.
ILookup<char, string> lookup = packages.ToLookup(
    p => p.Company[0], p => p.Company + " " + p.TrackingNumber);

// Iterate through each IGrouping in the Lookup.
foreach (IGrouping<char, string> packageGroup in lookup) {
  // Print the key value of the IGrouping.
  Console.WriteLine(packageGroup.Key);
  // Iterate through each value in the
  // IGrouping and print its value.
  foreach (string str in packageGroup) Console.WriteLine("    {0}", str);
}
/*
 *
C
Coho Vineyard 89453312
Contoso Pharmaceuticals 670053128
L
Lucerne Publishing 89112755
W
Wingtip Toys 299456122
Wide World Importers 4665518773*/

58.TryGetNonEnumeratedCount 尝试在不枚举的情况下获取序列中元素数量

int[] a = new int[]{1, 2, 3, 4, 5, 4, 3, 2, 1};
a.TryGetNonEnumeratedCount(out int theCount);
Console.WriteLine(theCount);  // 9

59.Union 联合(会去重)

public class ProductA : IEquatable<ProductA> {
  public string Name {
    get;
    set;
  }
  public int Code {
    get;
    set;
  }

  public bool Equals(ProductA other) {
    if (other is null) return false;

    return this.Name == other.Name && this.Code == other.Code;
  }

  public override bool Equals(object obj) => Equals(obj as ProductA);
  public override int GetHashCode() =>(Name, Code).GetHashCode();
}
int[] ints1 = {5, 3, 9, 7, 5, 9, 3, 7};
int[] ints2 = {8, 3, 6, 4, 4, 9, 1, 0};

IEnumerable<int> union
= ints1.Union(ints2);

foreach (int num in union) {
  Console.Write("{0} ", num);  // 5 3 9 7 8 6 4 1 0
}
Console.WriteLine();

ProductA[] store1 = {new ProductA{Name = "apple", Code = 9},
                     new ProductA{Name = "orange", Code = 4}};

ProductA[] store2 = {new ProductA{Name = "apple", Code = 9},
                     new ProductA{Name = "lemon", Code = 12}};
IEnumerable<ProductA> union2 = store1.Union(store2);
Console.WriteLine(JsonConvert.SerializeObject(
    union2));  //[{"Name":"apple","Code":9},{"Name":"orange","Code":4},{"Name":"lemon","Code":12}]

60.UnionBy 将函数处理后的结果联合

var a = new[]{1, 2, 3, 4, 5, 6, 7};
var b = new[]{4, 5, 6, 7, 8, 9, 10};
Func<int, string> transform = i => i.ToString();

var result = a.UnionBy(b, transform);

Console.WriteLine(JsonConvert.SerializeObject(
    result));  //"1", "2", "3", "4", "5", "6", "7", "8", "9", "10"

61.Where

List<string> fruits2 =
    new List<string>{"apple",  "passionfruit", "banana", "mango",
                     "orange", "blueberry",    "grape",  "strawberry"};

IEnumerable<string> query = fruits2.Where(fruit => fruit.Length < 6);

foreach (string fruit in query) {
  Console.WriteLine(fruit);
}
// apple mango grape

62.Zip 结合两个集合

int[] numbers = {1, 2, 3, 4};
string[] words = {"one", "two", "three"};

var numbersAndWords =
    numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords) Console.WriteLine(item);
/*
 * 1 one
 * 2 two
 * 3 three
 */
#
首页      CSharp      Enumerable Class (C#)

于梦想齐行

Enumerable Class (C#)
提供一组静态方法用于查询实现IEnumerable<T>的对象。 Methods 1.Aggregate 在序列上应用累加器函数。指定的值作为初始累加器值,指定的函数用于选择结果。 List<St…
扫描二维码继续阅读
2022-08-30
近期文章
近期评论