Q:

Write a program in C# to display the number and frequency of number from given array in LINQ Query

belongs to collection: All LINQ programs in C# with examples

0

Write a program in C# to display the number and frequency of number from given array in LINQ Query

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

I have used Visual Studio 2012 for debugging purpose. But you can use any version of visul studio as per your availability.

using System;
using System.Linq;
using System.Collections.Generic;
 
class LinqExercise
{
    static void Main(string[] args)
    {
        int[] arr = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 2, 3, 10 };       
        Console.Write("The numbers in the array  are : \n");
        Console.Write("1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 2, 3, 10 \n");
 
        var n = from x in arr
                group x by x into y
                select y;
        Console.WriteLine("\nThe number and the frequency are : \n");
        foreach (var arrno in n)
        {
            Console.WriteLine("Number " + arrno.Key + " appears " + arrno.Count() + " times");
        }
        Console.ReadLine();
    }
}

Result:

The numbers in the array  are : 

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 4, 5, 2, 3, 10 

The number and the frequency are : 

Number 1 appears 1 times

Number 2 appears 2 times

Number 3 appears 2 times

Number 4 appears 2 times

Number 5 appears 2 times

Number 6 appears 1 times

Number 7 appears 1 times

Number 8 appears 1 timesNumber 9 appears 1 times

Number 10 appears 2 times

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Write a program in C# to display the characters an... >>
<< Write a program in C# to display the top n-th reco...