使用命令使用linq查询

时间:2014-03-19 08:56:40

标签: c# linq

我有4列,facility0id,名称,日期,数量。我这里几乎没有问题

如何根据数量使用orderby。我想找到前三排。任何人都可以提供帮助,谢谢

    DataClassesDataContext db = new DataClassesDataContext();

    var query = from p in db.Facilities
                join v in db.Reservations on p.facilities_id equals v.facilities_id
                join c in db.Reservation_Details on v.reservation_id equals    
                c.resevation_id
                where SqlMethods.Like(c.date, "%" + DropDownList1.Text + "%")
                select new
                {
                    p.facilities_id,
                    p.name,
                    c.date,
                    Quantity = p.Reservations.Count()

                };

    GridView1.DataSource = query.GroupBy(x => x.facilities_id)
                       .Select(g => g.First())
                       .ToList();

    GridView1.DataBind();

    int totalRowsCount = GridView1.Rows.Count;
    Label2.Text = DateTime.Now.ToShortDateString();
    Label3.Text = totalRowsCount.ToString() + " record(s)";
    Label4.Text = DropDownList1.Text;

我的数据库中的数据

 facilities_id      name       date      Quantity
   F001              cc     12-12-2014     3
   F002              vv     12-12-2014     2
   F003              gg     12-12-2014     1
   F004              bb     12-12-2014     5

这是我的预期输出

  facilities_id     name       date     Quantity
   F004              bb     12-12-2014     5
   F001              cc     12-12-2014     3
   F002              vv     12-12-2014     2

3 个答案:

答案 0 :(得分:4)

使用OrderByDescendingQuantity降序排列记录,然后Take首先3记录:

query.GroupBy(x => x.facilities_id)
     .Select(g => g.First())
     .OrderByDescending(x => x.Quantity)
     .Take(3)
     .ToList();

答案 1 :(得分:1)

用于降序“OrderByDescending”

.OrderByDescending(x => x.Quantity);

用于升序“OrderBy”

OrderBy(x => x.Quantity);

答案 2 :(得分:0)

您需要首先按列数量降序使用订单,然后前三行