LINQ:从每个组中选择最新

时间:2016-07-07 16:08:13

标签: c# linq

所以,我知道我非常生疏,但我从未想过如果花费数小时尝试不同的解决方案,这将是如此困难。在删除特定子句然后将其绑定到网格后,我尝试从每个组中选择最新记录。基本上没有运气......这是我离开的地方:

var widgets = db.Updates
            .GroupBy(c => c.widgetType)
            .SelectMany(s => s)
            .Where(c => c.Sold.Equals(false))
            .OrderByDescending(x => x.TimeStamp)
            .FirstOrDefault();
        var list = new List<Update>() {widgets};
            widgetsGrid.DataSource = list;            
            widgetsGrid.DataBind();

我添加了强制转换列表,因为我收到了数据类型错误,目前它只返回所有记录的最后一项,而不是每组中的最后一项。

提前感谢您的帮助!!!

4 个答案:

答案 0 :(得分:1)

OrderByDescending应该在每个组的级别上。您也不需要SelectMany,因为这会将这些群体加入到单位列表中。

var widgets = Updates
        .GroupBy(c => c.widgetType)
        .Where(c => c.Sold.Equals(false))
        .Select(x => x.OrderByDescending(y => y.TimeStamp).First());

答案 1 :(得分:0)

         var widgets = db.Updates
        .GroupBy(c => c.widgetType)
        .SelectMany(s => s)
        .Where(c => c.Sold.Equals(false))
        .OrderByDescending(x => x.TimeStamp)
        .Select(y=>y.First());

    var list = new List<Update>() {widgets};
        widgetsGrid.DataSource = list;            
        widgetsGrid.DataBind();

答案 2 :(得分:0)

您需要做的关键似乎是顺序并从列表中选择第一项。这是一个示例程序:

class Program
{
    static void Main(string[] args)
    {
        var foodOrders = new List<FoodOrder>
        {
            new FoodOrder { FoodName = "hotdog", OrderDate = new DateTime(2016, 7, 7) },
            new FoodOrder { FoodName = "hamburger", OrderDate = new DateTime(2016, 7, 6) },
            new FoodOrder { FoodName = "taco", OrderDate = new DateTime(2016, 7, 5) },
        };

        var mostRecentFoodOrder = foodOrders.OrderByDescending(f => f.OrderDate).First().FoodName;
        Console.WriteLine(mostRecentFoodOrder);

        //cmd
        //hotdog
        //Press any key to continue . . .
    }
}

class FoodOrder
{
    public string FoodName { get; set; }
    public DateTime OrderDate { get; set; }
}

答案 3 :(得分:0)

var widgets = db.Updates
          .Where(c => c.Sold.Equals(false))
          .GroupBy(c => c.widgetType)       
      .Select(x => x.OrderByDescending(y => y.TimeStamp).First()).ToList();
       widgetGrid.DataSource = widgets;
       widgetGrid.DataBind();

我已经在网上看到了这个问题一百次......这对我有用。礼貌,非常感谢@Ahmad Ibrahim