Average

In this chapter you will learn:

  1. How to use Average operator
  2. Using Average to get the average length of the words in the string array

What is Average operator

Selector typeResult type
decimaldecimal
int, long, float, doubledouble
using System;//from  ja v  a2 s  .c om
using System.Linq;

class Program
{
    static void Main()
    {
        decimal[] numbers = { 3, 4, 8 };
        decimal average = numbers.Average();  // 5  (mean value)

        Console.WriteLine(average);

        double avg = new int[] { 3, 4 }.Average();  // 3.5
        Console.WriteLine(avg);

    }
}

The output:

Average length of words

using System;/*j ava2s  .  co m*/
using System.Linq;

public class MainClass
{
    public static void Main()
    {
        string[] words = { "ch", "a", "blue" };

        double averageLength = words.Average(w => w.Length);

        Console.WriteLine("The average word length is {0} characters.", averageLength);
    }
}

Next chapter...

What you will learn in the next chapter:

  1. Use Linq Cast to convert array to IEnumerable
  2. Cast to int
  3. Cast and catch exception
Home » C# Tutorial » Linq Operators
Aggregate
Aggregate with seed
Aggregate string value
All
Any
Average
Cast
Concat
Contains
Count
DefaultIfEmpty
Distinct
ElementAt
ElementAtOrDefault
Empty
Except
FindAll
First
FirstOrDefault
GroupBy
Intersect
Last
LastOrDefault
LongCount
Max
Min
OfType
OrderBy
OrderByDescending
Range
Repeat
Reverse
SelectMany
SequenceEqual
Single
SingleOrDefault
Skip
SkipWhile
Sum
Take
TakeWhile
ThenBy
ThenByDescending
ToArray
ToList
Zip