Solved

How to write LINQ query

Posted on 2014-12-22
4
89 Views
Last Modified: 2016-02-15
Hi, yet another LINQ query. My apologies I cannot get the hang of this. This should be simple. My code is below.
Thank you
John

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            Dictionary<int, List<Single>> test = new Dictionary<int, List<Single>>();

            test.Add(1, new List<Single> { 1f, 2f, 3f, 4f });
            test.Add(15, new List<Single> { 1.1f, 2f });
            test.Add(99, new List<Single> { 1.1f, 1f, 2f });

            int totalNumberOfValues = test.Sum(n => n.Value.Count());   //returns 9 which is correct

            //the distinct values are 1f, 2f, 3f, 4f, 1.1f, counting them there are 5 values
            //I want to count them
            int totalNumberOfDistinctValue = what goes here;      //I want this to be 5
        }
    }
}

Open in new window

0
Comment
Question by:John Bolter
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
4 Comments
 
LVL 33

Accepted Solution

by:
it_saige earned 500 total points
ID: 40513104
You would use:
int totalNumberOfDistinctValue = test.SelectMany(n => n.Value).Distinct().Count();

Open in new window


Example -
using System;
using System.Collections.Generic;
using System.Linq;

namespace EE_Q28585282
{
	class Program
	{
		static void Main(string[] args)
		{
			Dictionary<int, List<Single>> test = new Dictionary<int, List<Single>>();

			test.Add(1, new List<Single> { 1f, 2f, 3f, 4f });
			test.Add(15, new List<Single> { 1.1f, 2f });
			test.Add(99, new List<Single> { 1.1f, 1f, 2f });

			int totalNumberOfValues = test.Sum(n => n.Value.Count());   //returns 9 which is correct
			Console.WriteLine(string.Format("Total number of values: {0}", totalNumberOfValues));

			//the distinct values are 1f, 2f, 3f, 4f, 1.1f, counting them there are 5 values
			//I want to count them
			int totalNumberOfDistinctValue = test.SelectMany(n => n.Value).Distinct().Count();      //I want this to be 5
			Console.WriteLine(string.Format("Total number of distinct values: {0}", totalNumberOfDistinctValue));
			Console.ReadLine();
		}
	}
}

Open in new window


Produces the following output -Capture.JPG
More on SelectMany - http://msdn.microsoft.com/en-us/library/system.linq.enumerable.selectmany%28v=vs.100%29.aspx

-saige-
0
 

Author Closing Comment

by:John Bolter
ID: 40513139
Oh of course.

I even wrote

test.Select(n => n.Value).Distinct().Count();

that didn't work. I wasn't even away of SelectMany.

Thank you!
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 40513231
If you're interested in what those distinct values are, and how many of them there were, then:
        static void Main(string[] args)
        {
            Dictionary<int, List<Single>> test = new Dictionary<int, List<Single>>();

            test.Add(1, new List<Single> { 1f, 2f, 3f, 4f });
            test.Add(15, new List<Single> { 1.1f, 2f });
            test.Add(99, new List<Single> { 1.1f, 1f, 2f });

            int totalNumberOfValues = test.Sum(n => n.Value.Count());  

            var distinctValuesWithCount = test.SelectMany(x => x.Value) // flatten the dictionary values to a single List<Single>
                .GroupBy(x => x) // grouped by each Single in the List
                .Select(group => new // create an anonymous type with the value and number of occurrences of that Single
                {
                    Value = group.Key,
                    Count = group.Count()
                })
                .OrderBy(x => x.Value); // sorted ascending by the Single

            int totalNumberOfDistinctValue = distinctValuesWithCount.Count();

            Console.WriteLine("totalNumberOfDistinctValue = " + totalNumberOfDistinctValue.ToString());
            foreach(var g in distinctValuesWithCount)
            {
                Console.WriteLine("value = " + g.Value.ToString() + ", Count = " + g.Count.ToString());
            }
            Console.ReadLine();
        }

Open in new window


Output:
totalNumberOfDistinctValue = 5
value = 1, Count = 2
value = 1.1, Count = 2
value = 2, Count = 3
value = 3, Count = 1
value = 4, Count = 1

Open in new window

0
 

Author Comment

by:John Bolter
ID: 40514441
Thanks,
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
What Does This C# Code Block Do? 5 73
Changes to XXX.exe.config file are not retrieved on restart. 3 50
Please explain purpose of GZIP 4 60
Set custom font WPF 2 21
This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

726 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question