John Bolter
asked on
How to write LINQ query
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
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
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
If you're interested in what those distinct values are, and how many of them there were, then:
Output:
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();
}
Output:
totalNumberOfDistinctValue = 5
value = 1, Count = 2
value = 1.1, Count = 2
value = 2, Count = 3
value = 3, Count = 1
value = 4, Count = 1
ASKER
Thanks,
ASKER
I even wrote
test.Select(n => n.Value).Distinct().Count(
that didn't work. I wasn't even away of SelectMany.
Thank you!