0
var data = new[] {
 new { Id = 0, Cat = 1, Price = 2 },
 new { Id = 1, Cat = 1, Price = 10 },
 new { Id = 2, Cat = 1, Price = 30 },
 new { Id = 3, Cat = 2, Price = 50 },
 new { Id = 4, Cat = 2, Price = 120 },
 new { Id = 5, Cat = 2, Price = 200 },
 new { Id = 6, Cat = 2, Price = 1024 },
};

var ranges = new[] { 10, 50, 100, 500 };

必要な出力は、カテゴリに従って使用される範囲以上でグループ化された価格カウントです。 (1 つの linq ステートメントで)

cat    range       count
-------------------------------------
1       10           2    (In 1. categories there is 2 item that price >= 10(range) [10;30]) 
2       10           4    (In 2. categories there is 4 item that price >= 10(range) [50;120;200;1024]) 
2       50           4    ....
2      100           3    ....
2      500           1    (In 2. categories there is 1 item that price >= 500(range) [1024]) 
4

2 に答える 2

4

これを試して:

var data = new[] {
 new { Id = 0, Cat = 1, Price = 2 },
 new { Id = 1, Cat = 1, Price = 10 },
 new { Id = 2, Cat = 1, Price = 30 },
 new { Id = 3, Cat = 2, Price = 50 },
 new { Id = 4, Cat = 2, Price = 120 },
 new { Id = 5, Cat = 2, Price = 200 },
 new { Id = 6, Cat = 2, Price = 1024 },
};

var ranges = new[] { 10, 50, 100, 500 };

var result = from r in ranges
        from g in data
        where g.Price >= r
        select new {g.Cat, Price=r};

var groupedData = 
        from d in result
        group d by new{d.Cat, d.Price} into g
        select new{Cat=g.Key.Cat, Price=g.Key.Price, TotalCount=g.Count()};
于 2012-12-12T11:38:07.087 に答える
4

これはうまくいくはずです:

var values =
data.SelectMany(x => ranges.Where(y => x.Price >= y)
                           .Select(y => new { Record = x, Range = y }))
    .GroupBy(x => new { Cat = x.Record.Cat, Range = x.Range })
    .Select(x => new { Cat = x.Key.Cat, Range = x.Key.Range, Count = x.Count()});

結果:

{ Cat = 1, Range = 10,  Count = 2 }
{ Cat = 2, Range = 10,  Count = 4 }
{ Cat = 2, Range = 50,  Count = 4 }
{ Cat = 2, Range = 100, Count = 3 }
{ Cat = 2, Range = 500, Count = 1 }
于 2012-12-12T11:40:17.350 に答える