Reputation: 1027
hi i have collection list named ~runs~
class CRun {
int slideQuestion;
int studentId;
string answer;
}
public static List<CRun> runs = new List<CRun>();
this is how i add data to collection list
myRun.slideQuestion = 1;
myRun.studentId = 15;
myRun.answer = 2;
0 = { 1, 15, 2}
1 = { 1, 12, 5}
2 = { 2, 15, 3}
3 = { 2, 12, 4}
then i have data like this { 1, 15, 1}
i wanna replace list[0] (same slideQuestion & studentID) so it's become
**0 = {1, 15, 1}**
1 = { 1, 12, 5}
2 = { 2, 15, 3}
3 = { 2, 12, 4}
i wanna make condition like this
if ~slideQuestion~ AND ~studentID~ already in list
//replace answer in some location
else (add data)
runs.add(myRun);
how to do it?
Upvotes: 0
Views: 116
Reputation: 1743
Using linq:
var r = runs.FirstOrDefault(c => c.slideQuestion == 10 && c.studentId == 15);
if (r != null)
{
r.answer = "something";
}
else
{
runs.Add(new CRun
{
slideQuestion = 10,
studentId = 15,
answer = "something"
});
}
Change your class to this:
class CRun {
public int slideQuestion { get; set; }
public int studentId { get; set; }
public string answer { get; set; }
}
You cannot access the class fields if they are private. Change them to auto-properties.
Upvotes: 1
Reputation: 4363
Assuming this is the new slidequestion, student id, and the answer you want to replace are in these variables
int slideQuestion = 1;
int studentId = 15;
string newAnswer = "1";
Here is how you search for run and update with the new answer if it exists or create a new run
var runInList = (from run in runs where run.SlideQuestion == slideQuestion && studentId == studentId select run).FirstOrDefault();
if (runInList != null)
{
runInList.Answer = newAnswer;
}
else
{
runs.Add(new CRun { SlideQuestion = slideQuestion, StudentId = studentId, Answer = newAnswer });
}
Upvotes: 1
Reputation: 233487
Here's how to replace the first element in the list:
runs[0] = newValue;
Upvotes: 1