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);
}
}
How do I assign some increment number to the IndexNo properties, from the list? My expected output is:
Thanks.
Re comment:
Actually I was hoping to assign the increment IndexNo, after the collection has been created.
then just loop:
int i = 1;
foreach(var comment in comments) comment.IndexNo = i++;
Since you are hard-coding the offset, you could just hard-code:
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 },
};
If you want something less hard-coded, how about:
var comments = (from i in Enumerable.Range(1,4)
select new Comment {
CreatedOn = DateTime.Now.AddMinutes(i), IndexNo = i
}).ToList();
or simpler:
var comments = new List<Comment>(4);
for(int i = 1 ; i < 5 ; i++) {
comments.Add(new Comment {
CreatedOn = DateTime.Now.AddMinutes(i), IndexNo = i });
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With