Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add increment index number in a collection

Tags:

c#

collections

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:

  • 15 April 2004 2:37pm ~ 1
  • 15 April 2004 2:38pm ~ 2
  • 15 April 2004 2:39pm ~ 3
  • 15 April 2004 2:40pm ~ 4

Thanks.

like image 891
hypokerit Avatar asked Jan 18 '26 21:01

hypokerit


1 Answers

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 });
}
like image 55
Marc Gravell Avatar answered Jan 20 '26 11:01

Marc Gravell