替换列表中的值

时间:2014-03-26 06:42:40

标签: c# list

嗨,我的收藏清单名为~shun~

 class CRun {
   int slideQuestion;
   int studentId;
   string answer;
 }

 public static List<CRun> runs = new List<CRun>(); 

这是我如何将数据添加到收藏列表

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}

然后我有这样的数据{1,15,1} 我想替换list [0](同样的slideQuestion&amp; studentID),以便它成为

**0 = {1, 15, 1}**
1 = { 1, 12, 5}
2 = { 2, 15, 3}
3 = { 2, 12, 4}

我想做这样的条件

if ~slideQuestion~ AND ~studentID~ already in list 
    //replace answer in some location
else (add data)
    runs.add(myRun);

怎么做?

3 个答案:

答案 0 :(得分:1)

以下是如何替换列表中的第一个元素:

runs[0] = newValue;

答案 1 :(得分:1)

使用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"
     });   
 }

将您的班级更改为:

class CRun {
   public int slideQuestion { get; set; }
   public  int studentId { get; set; }
   public  string answer { get; set; }
}

如果类字段是私有的,则无法访问它们。将它们更改为自动属性。

答案 2 :(得分:1)

假设这是新的幻灯片,学生ID和您要替换的答案都在这些变量中

int slideQuestion = 1;
int studentId = 15;
string newAnswer = "1";

以下是如何使用新答案搜索运行和更新(如果存在)或创建新运行

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 });
}