gpt4 book ai didi

c# - 在集合中添加增量索引号

转载 作者:太空宇宙 更新时间:2023-11-03 16:15:09 25 4
gpt4 key购买 nike

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:38 ~ 2
  • 2004 年 4 月 15 日下午 2:39 ~ 3
  • 2004 年 4 月 15 日下午 2:40 ~ 4

谢谢。

最佳答案

回复评论:

Actually I was hoping to assign the increment IndexNo, after the collection has been created.

然后循环:

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 });
}

关于c# - 在集合中添加增量索引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16009157/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com