所以,我知道我很生疏,但我从未想过尽管花了几个小时尝试不同的解决方案,但这会如此困难。 在消除特定子句然后将其绑定到网格后,我正在尝试从每个组中选择最新记录。 基本上没有运气...这是我离开的地方:
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();
由于我收到数据类型错误,我将强制转换为列表,目前它仅返回所有记录的最后一项,而不是每个组中的最后一项。
提前感谢您的任何帮助!!
OrderByDescending
应该在每个组的级别上。您也不需要SelectMany
因为这会将组重新加入到平面列表中。
var widgets = Updates
.GroupBy(c => c.widgetType)
.Where(c => c.Sold.Equals(false))
.Select(x => x.OrderByDescending(y => y.TimeStamp).First());
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();
似乎您需要做的关键事情是按顺序并从列表中选择第一项。下面是一个示例程序:
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; }
}
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提供并非常感谢