C# 如何使用 LINQ 从实体加载最后一条记录?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19121663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 14:09:33  来源:igfitidea点击:

How to load just the last record from entity with LINQ?

c#asp.netlinqentitydatamodel

提问by amin

I want to fetch value of field named "Gram" from the last record and put its value into a variable, without using any conditions.

我想从最后一条记录中获取名为“Gram”的字段的值并将其值放入一个变量中,而不使用任何条件。

First I tried

首先我试过

int value = int.Parse(Entity.TblGold.LastOrDefault().Gram.ToString());

Second I tried

第二次我试过

int value = int.Parse(Entity.TblGold.Select(p => p.Gram).Last().ToString());

I just receive this exception:

我刚刚收到此异常:

LINQ to Entities does not recognize the method 'DataModel.TblGold LastOrDefault[TblGold](System.Linq.IQueryable``1[DataModel.TblGold])' method, and this method cannot be translated into a store expression.

LINQ to Entities does not recognize the method 'DataModel.TblGold LastOrDefault[TblGold](System.Linq.IQueryable``1[DataModel.TblGold])' method, and this method cannot be translated into a store expression.

采纳答案by Habib

Lastor LastOrDefaultare not supported in LINQ to Entities. You can either iterate your query using ToListor ToArrayand then apply Lastor you can order by descending and then use the Firstlike:

LastLastOrDefault在 LINQ to Entities 中不受支持。您可以使用ToListor迭代您的查询ToArray,然后应用,Last或者您可以按降序排序,然后使用First类似的方法:

int value = int.Parse(Entity.TblGold
                            .OrderByDescending(p => p.Gram)
                            .Select(r => r.Gram)
                            .First().ToString());

回答by Garrison Neely

You can't do it in one query, but you can do it in two.

你不能在一个查询中完成,但你可以在两个查询中完成。

var countOfRows = tbl.Count();

var lastRow = tbl.Skip(countOfRows - 1).FirstOrDefault();

回答by Bern

If the list is correctly ordered to grab the last item I'd simply reverse the list then grab the first (previously last) item:

如果列表正确排序以获取最后一个项目,我只需反转列表然后获取第一个(以前是最后一个)项目:

var gram = int.Parse(Entity.TblGold.Reverse().First().Gram.ToString());

回答by user4060204

You can use order by 1 == 1 and it works

您可以使用 order by 1 == 1 并且它有效

var countOfRows = tbl.Count();    
var lastRow = tbl.OrderBy(c => 1 == 1).Skip(countOfRows - 1).FirstOrDefault();