如何使用Linq向订单添加订单(autoIncrement)属性?

Eri*_*tas 4 c# linq anonymous-types

有:

初始化anonymouse集合(我会将其作为json发送)

var myCollection = new[]
{
    new
    {
        Code = 0,
        Name = "",
        OtherAttribute = ""
    }

}.ToList();

myCollection.Clear();
Run Code Online (Sandbox Code Playgroud)

并获取数据.

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();
Run Code Online (Sandbox Code Playgroud)

我想添加一个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();
Run Code Online (Sandbox Code Playgroud)

Sam*_*Sam 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();
Run Code Online (Sandbox Code Playgroud)


Did*_*xis 1

正如西蒙在他的评论中所说,请考虑以下示例(尽管是人为的):

int i = 0;
var collection = Enumerable.Range(0, 10).Select(x => new { Id = ++i });
Run Code Online (Sandbox Code Playgroud)