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時38分~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 に答える