'Loop through properties and set the value of each property as an item in a list, print the list and then set the value again? C#
I currently have this loop:
if (lists.Date.Count() == 0)
{
message = "There Have Been No Merged Pull Requests In This Repository";
}
else
{
for (int i = 0; i < lists.Date.Count(); i++)
PullRequests = new List<PullRequestDetails>
{
new PullRequestDetails()
{
Title = lists.ShortRequestTitle[i],
Name = lists.Name[i],
Date = lists.Date[i],
CommitLink = lists.ShortCommitList[i],
},
};
}
which takes strings from lists and sets them in this model:
public class PullRequestDetails
{
public string? Title { get; set; }
public string? Name { get; set; }
public string? Date { get; set; }
public string? CommitLink { get; set; }
}
I want my HTML to display every item from the list when the button is clicked, but currently it is only displaying the last item from the list:
@if (Model.PullRequests != null)
{
@foreach (var requests in Model.PullRequests)
{
<tbody>
<tr>
<td>@requests.Title</td>
<td>@requests.Name</td>
<td>@requests.Date</td>
<td><a [email protected] target="_blank"> Link </a></td>
</tr>
</tbody>
}
}
This works when I manually add each value of the list, but his gives an out of range exception when there are less or more than 4 values in each list (which there are in most cases):
if (lists.Date.Count() == 0)
{
html = "There Have Been No Merged Pull Requests In This Repository";
}
else
{
for (int i = 0; i < lists.Date.Count(); i++)
PullRequests = new List<PullRequestDetails>
{
new PullRequestDetails()
{
Title = lists.ShortRequestTitle[0],
Name = lists.Name[0],
Date = lists.Date[0],
CommitLink = lists.ShortCommitList[0]
},
new PullRequestDetails()
{
Title = lists.ShortRequestTitle[1],
Name = lists.Name[1],
Date = lists.Date[1],
CommitLink = lists.ShortCommitList[1]
},
new PullRequestDetails()
{
Title = lists.ShortRequestTitle[2],
Name = lists.Name[2],
Date = lists.Date[2],
CommitLink = lists.ShortCommitList[2]
},
new PullRequestDetails()
{
Title = lists.ShortRequestTitle[3],
Name = lists.Name[3],
Date = lists.Date[3],
CommitLink = lists.ShortCommitList[3]
},
};
}
So how can I fix this with a loop?
Solution 1:[1]
Just as @Camilo Terevinto said you need too take the List instantiation out of the loop
if (lists.Date.Count() == 0)
{
message = "There Have Been No Merged Pull Requests In This Repository";
}
else
{
PullRequests = new List<PullRequestDetails>();
for (int i = 0; i < lists.Date.Count(); i++)
{
PullRequests.Add(new PullRequestDetails()
{
Title = lists.ShortRequestTitle[i],
Name = lists.Name[i],
Date = lists.Date[i],
CommitLink = lists.ShortCommitList[i]
});
};
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | J.Salas |
