views:

65

answers:

2

Having the following:

var categories = new List<double> {10,20,30,40};    // Note the 40 here...
var bundleA = new List<double> {10,20};
var bundleB = new List<double> {20,20,30}; 
var lots = new List<List<double>> {bundleA, bundleB};
var total = lots.Sum (l => l.Count);

var res = from lot in lots
            from bundle in lot
            join length in categories on bundle equals length into l
            group bundle by l
            into g
            select new {Length = g.Key.Single(), Dist = (double)g.Count() / total};
res.Dump();

The dump shows:

  • Length = 10 with Dist = 0.2
  • Length = 20 with Dist = 0.6
  • Length = 30 with Dist = 0.2

I am trying to have Length = 40 with Dist = 0 into the result but I can't figure it out.

Any help please?

+1  A: 

This should get it:

var res =   from length in categories
            let sm = lots.SelectMany(l => l)
            select new { length, dist = sm.Where(l => l == length).Count() / (double)sm.Count() };

The problem was you need to start with categories or any category that doesn't exist in the bundles will not exist in the result.

Stephan
Excellent! I never thought of using SelectMany... so simple! Thanks a lot!
Stecy
+1  A: 

How about:

        var res = from cat in categories
                  let bundle = lots.SelectMany(list => list)
                  let cnt = bundle.Count(n => n == cat)
                  select new { Length = cat, Dist = (double)cnt / total };
driis