我在数据库表中有一组记录,我们称之为组件表,它被定义为follows。
管理员可以使用disableflag禁用某些组件,disableflag是表的最后一列。如果禁用某个特定组件,它不应出现在用户的网格视图中。
我从数据库中获取数据并通过gridview显示here,如果您观察到SNo值不合规。
我用来检索数据的linq查询是:
var gridViewResults = from results in db.Components where results.DisableFlag == false
select new { SNo = results.SNo, ComponentNames = results.Component_Name, Size = results.Size__in_MB_, Price = results.Price__in_SEK_, TotalDownloads = results.Total_Downloads, Description = results.Description };
但我希望数据按顺序显示,SNo为1,2,3,4,而不依赖于数据库表SNO值:参考this。
我无法弄清楚如何使用linq查询来实现这个目标:
我试过这个问题:
(db.Components.AsEnumerable().Select((iterator)=> new{iterator.SNo + 1})
但我认为这很荒谬。有人可以帮我解决这个问题。
感谢您的期待。
答案 0 :(得分:2)
如果您绝对确定要忽略数据库编号(为什么输出数字,如果它们实际上并不对应?),您可以尝试以下操作:
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
});
编辑:来自How To Project a Line Number Into Linq Query Results
的替代解决方案EDIT2:修复SQL不支持的选择:Linq error - "NotSupportedException: Unsupported overload used for query operator 'Select'"
答案 1 :(得分:1)
大家好,这是最后的答案。约书亚做了所有的工作。非常感谢他。只想强调未来遇到同样问题的任何人的答案。如果有人想投票,请投票 Joshua
var gridViewData = from results in db.Components
where results.DisableFlag == false
select new
{
ComponentNames = results.Component_Name,
Size = results.Size__in_MB_,
Price = results.Price__in_SEK_,
TotalDownloads = results.Total_Downloads,
Description = results.Description
};
var gridViewResults = gridViewData.AsEnumerable().Select((item, index) => new
{
SNo = index + 1,
ComponentNames = item.ComponentNames,
Size = item.Size,
Price = item.Price,
TotalDownloads = item.TotalDownloads,
Description = item.Description
}).ToList();
这应该有用。