开发者

Using Linq and C#, how would I categorize a list of list and getting empty categories?

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?


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.


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 };
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜