1

以下にテーブルがあります-会社

  id name value year
    1  IBM   10   2011
    2  IBM   30   2012
    3  IBM   10   2012
    4  C     10   2010

レコードを名前でグループ化し、各グループから最大idを持つレコードを 1 つだけ返します。すべての結果は、年が 2011 年より大きい linq を使用して企業のリストに結合されます。私の例では、出力は「3 IBM 10 2012」になります。

私は何かを書きましたが、動作しません。

var a = from x in companies where x.year > 2011
                  group x by new {x.name, x.value, x.ID, x.year } into g
                  select new {
                                  g.Key.name,
                                  g.Key.value,
                                  g.Max(a=>a.ID),
                                  g.Key.value
                              };
 return a.ToList();
4

2 に答える 2

0

これを試して:

  var a = from x in companies
                where x.Year > 2011
                group x by new { x.Name } into g
                from x1 in companies
                where x1.ID == (from x2 in g select x2.ID).Max()
                select x1;   

または、より効率的なもの:

var a = from x in companies
                    where x.Year > 2011
                    group x by new { x.Name } into g
                    join x2 in companies on (from x3 in g select x3.ID).Max() equals x2.ID
                    select x2;  
于 2012-06-21T22:13:31.847 に答える
0

グループ化に ID を含めないでください。実際、会社名でグループ化するだけの場合は、他のプロパティも含めないでください。

// set up for testing
var companies =
    from c in new[]{"1,IBM,10,2011", "2,IBM,30,2012", "3,IBM,10,2012", "4,C,10,2010"}
    let cp = c.Split(',')
    select new {id=int.Parse(cp[0]), name=cp[1], value=int.Parse(cp[2]), year=int.Parse(cp[3])};

// query
var q = from x in companies where x.year > 2011
        group x by x.name into g
        let top = g.OrderByDescending(x => x.id).FirstOrDefault()
        select new {
                        top.name,
                        top.value,
                        top.id,
                        top.year
                    };
于 2012-06-21T21:55:14.243 に答える