LINQ Learning (5) Collection operations

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.