C# 如何使用Linq向集合添加订单(自动增量)属性?
具有: 初始化anonymouse集合(我会将其作为json发送) 并获取数据C# 如何使用Linq向集合添加订单(自动增量)属性?,c#,linq,anonymous-types,C#,Linq,Anonymous Types,具有: 初始化anonymouse集合(我会将其作为json发送) 并获取数据 myCollection = (from iPeople in ctx.Person join iAnotherTable in ctx.OtherTable on iPeople.Fk equals iAnotherTable.FK ... order by iPeople.Name as
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();
我想添加一个标识列,我需要有序的集合和从1到collection.count的计数。用于将此计数器绑定到表(jtable)中的列
正如西蒙在他的评论中所说的,考虑下面的,尽管做作的例子:
int i = 0;
var collection = Enumerable.Range(0, 10).Select(x => new { Id = ++i });
正如Simon在评论中所建议的那样,这可能如下所示:
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();
执行此类代码时是否有任何问题?如果使用linq to entities或linq to sql,请从服务器获取数据并将其列出。 这个答案很可能不会转换成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();
List myCollection=new List();
myCollection.Add(“你好”);
myCollection.Add(“世界”);
var result=myCollection.Select((s,i)=>new{Identity=i,Value=s}).ToList();
一个帮助我实现相同目标的解决方案:
创建一个单独的函数,如下所示:
private int getMaterialOrder(参考int-order)
{
退货单++;
}
然后在linq查询中调用它,如:
。。。
选择new MaterialItem(){Order=getMaterialOrder(参考顺序),
...
您可能想得太多了。是否有任何东西阻止您使用局部计数器变量来设置标识?例如:identity=counter++
?@SimonWhitehead Nothing但我不想在获取后再次迭代整个列表。如果我可以使用Linq来完成,那就太好了。您不必再次迭代。您可以在内部完成LINQ查询——正如我在上一篇评论中所展示的。那么为什么不干脆Select(x=>new{Id=x});
?@Roy,这里的想法是使用一个外部计数I
,它可以在Select()中递增I++
。当然,您可以在我的示例中使用x
,但OP的源集合不是可枚举的.Range
构造。这就是为什么我说这是一个人为的示例:)是的,它抛出了我表达式树可能不包含赋值运算符
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();
List<string> myCollection = new List<string>();
myCollection.Add("hello");
myCollection.Add("world");
var result = myCollection.Select((s, i) => new { Identity = i, Value = s }).ToList();