2
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 属性分配一些增量编号?我的预期输出是:

  • 2004 年 4 月 15 日下午 2:37 ~ 1
  • 2004 年 4 月 15 日 2:38pm ~ 2
  • 2004 年 4 月 15 日下午 2:39 ~ 3
  • 2004 年 4 月 15 日下午 2:40 ~ 4

谢谢。

4

2 回答 2

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 });
}
于 2013-04-15T06:46:27.587 回答
-1

假设您要修改集合中的现有对象:

for (int i = 0; i < comments.Count; ++i)
    comments[i].IndexNo = i+1;
于 2013-04-15T06:55:38.570 回答