This article describes the collection operations for LINQ and continues to use the data sources described in the LINQ Learning (3) syntax structure.
Count/longcount
Count/longcount returns the number of elements in the result set, and the return type is Int/long.
The prototype is:
public static int Count<TSource>(this IEnumerable<TSource> source[, Func<TSource, bool> predicate])
Number of students whose name is longer than four characters:
var result = (from student in DataSource.Students
select student).Count(stu => { return stu.Name.Length > 4; }); // result: 1
Sum/Min/Max/Average
Returns the size, minimum, maximum, and average of the result set element or its properties, respectively.
Sum: Returns the sum of the collection elements that must be a basic value type or a nullable type for the collection elements that participate in the calculation.
Calculate Total Score:
var result = (from score in Datasource.scores
Select score). Sum (score => {return score). Value; });
Min/max: The maximum or minimum value of a result set element that requires the collection element to implement a icomparable<t> or IComparable interface.
Select the highest grade:
var result = (from score in DataSource.Scores
select score).Max(score => { return score.Value; }); // result: 96
Average: Returns the average of the collection element, the collection element that participates in the calculation must be a basic value type or a nullable type.
Calculate average score:
var result = (from score in DataSource.Scores
select score).Average(score => { return score.Value; }).ToString("F2"); // result: 75.23
Union
Union two sets with identical or similar elements, without removing duplicate elements.
The Union prototype is:
public static IEnumerable<TSource> Union<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second)
var result = DataSource.Students.Union(DataSource.Students2);
Result: A collection of all elements of a two collection.