public class Comment
{
public int IndexNo {get;set;}
public DateTime CreatedOn {get;set;}
}
static void Main()
{
int i = 0;
var comments = new List<Comment>()
{
new Comment() { CreatedOn = DateTime.Now.AddMinutes(1) },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(2) },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(3) },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(4) },
};
// Not very nice solution..
var foos = new List<Comment>();
foreach(var foo in comments.orderby(c=> c.createdOn))
{
foo.IndexNo = ++i;
foos.add(foo);
}
}
如何从列表中为IndexNo属性分配一些增量编号? 我的预期输出是:
感谢。
答案 0 :(得分:1)
评论:
实际上我希望在创建集合后分配增量IndexNo。
然后循环:
int i = 1;
foreach(var comment in comments) comment.IndexNo = i++;
由于您正在对偏移进行硬编码,因此您可以进行硬编码:
var comments = new List<Comment>() {
new Comment() { CreatedOn = DateTime.Now.AddMinutes(1), IndexNo = 1 },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(2), IndexNo = 2 },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(3), IndexNo = 3 },
new Comment() { CreatedOn = DateTime.Now.AddMinutes(4), IndexNo = 4 },
};
如果你想要一些不太硬编码的东西,那么:
var comments = (from i in Enumerable.Range(1,4)
select new Comment {
CreatedOn = DateTime.Now.AddMinutes(i), IndexNo = i
}).ToList();
或更简单:
var comments = new List<Comment>(4);
for(int i = 1 ; i < 5 ; i++) {
comments.Add(new Comment {
CreatedOn = DateTime.Now.AddMinutes(i), IndexNo = i });
}
答案 1 :(得分:-1)
假设您要修改集合中的现有对象:
for (int i = 0; i < comments.Count; ++i)
comments[i].IndexNo = i+1;