有:
初始化anonymouse集合(我会将其作为json发送)
var myCollection = new[]
{
new
{
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection.Clear();
获取数据。
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
我想添加一个Identity列,我需要订购该集合,并从1计数到collection.count。用于将此计数器绑定到表(jtable)中的列。
var myCollection = new[]
{
new
{
Identity = 0,
Code = 0,
Name = "",
OtherAttribute = ""
}
}.ToList();
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = Enum.Range(1 to n)//Here I don´t know how to do; in pl/sql would be rownum, but in Linq to SQL how?
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
答案 0 :(得分:5)
如果您使用linq实体或linq to sql,请从服务器和ToList()获取数据。 很可能这个答案不会转换为sql,但我还没有尝试过。
List<string> myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("world");
var result = myCollection.Select((s, i) => new { Identity = i, Value = s }).ToList();
答案 1 :(得分:2)
正如西蒙在评论中所说,这可能如下所示:
int counter = 0; //or 1.
myCollection = (from iPeople in ctx.Person
join iAnotherTable in ctx.OtherTable
on iPeople.Fk equals iAnotherTable.FK
...
order by iPeople.Name ascending
select new
{
Identity = counter++,
Code = iPeople.Code,
Name = iPeople.Name,
OtherAttribute = iAnotherTable.OtherAtribute
}).ToList();
执行这种代码有什么问题吗?
答案 2 :(得分:0)
正如西蒙在评论中所说的那样,考虑以下几点,尽管是做作的例子:
int i = 0;
var collection = Enumerable.Range(0, 10).Select(x => new { Id = ++i });
答案 3 :(得分:0)
帮助我实现相同目标的一个解决方案: 像这样创建一个单独的函数:
private int getMaterialOrder(ref int order)
{
return order++;
}
然后在您的 linq 查询中调用它,例如:
...
select new MaterialItem() { Order=getMaterialOrder(ref order),
...