您可以做的是首先找到要更新的Index,使用该Index 取出元组,然后再次使用该Index 为列表提供更新后的元组。
类似:
static void Main(string[] args)
{
var questions = new List<(ulong channel, ulong user, object answer)>
{
(1, 1, 1),
(2, 2, 2),
(3, 3, 3),
(4, 4, 4)
};
foreach (var (channel, user, answer) in questions)
{
Console.WriteLine(answer);
}
var channel3Index = questions.FindIndex((obj) => obj.channel == 3);
if (channel3Index > -1)
{
var question = questions[channel3Index];
question.answer = 666;
questions[channel3Index] = question;
}
foreach (var (channel, user, answer) in questions)
{
Console.WriteLine(answer);
}
Console.ReadKey();
}
您必须首先更新它,然后用现有的替换它的原因是因为您使用的是 ValueTuples,它们是值类型。见:https://docs.microsoft.com/en-us/dotnet/api/system.valuetuple?redirectedfrom=MSDN&view=netframework-4.8
编辑:
如果您不想在 List 中使用值类型,请使用引用类型。一个简单的类就可以了。
class Program
{
public class Question
{
public ulong Channel { get; set; }
public ulong User { get; set; }
public Object Answer { get; set; }
}
static void Main(string[] args)
{
var questions = new List<Question>
{
new Question
{
Channel = 1,
User = 1,
Answer = 1
},
new Question
{
Channel = 2,
User = 2,
Answer = 2
},
new Question
{
Channel = 3,
User = 3,
Answer = 3
},
};
foreach (var question in questions)
{
Console.WriteLine(question.Answer);
}
var channel3Index = questions.FindIndex((obj) => obj.Channel == 3);
if (channel3Index > -1)
{
questions[channel3Index].Answer = 666;
}
foreach (var question in questions)
{
Console.WriteLine(question.Answer);
}
Console.ReadKey();
}
}