猿问

带有 For-Each 循环的元组

我不确定我在这里做错了什么,或者是否真的有问题。


这可能完全是一个疏忽,这就是为什么我将它发送给社区看一看。


我正在客户端创建一个ListofTuple<T,Boolean>并通过 REST JSON 返回到 WCF。我在服务器端得到的值非常好。但是,当我尝试在for each循环中使用它们时,这些项目显示为NULL并出错。


有趣的是,我for each用经典for循环替换了循环,代码完美地运行在文件中。


下面是我正在使用的代码。还附上图像,其中包含有关我放在这里的场景的详细信息。


//This code fails

foreach (Tuple<Candidate, Boolean> cand in candidateList) //candidateList has got items perfectly in it.

{

  Candidate cd = cand.Item1; //cand comes out as NULL

    if (cd.IsShortlisted)

       InsertShortCandidates(jobPost.JobID.ToString(), cd.UserID, cd.MatchingScore.ToString());

    else

       RemoveShortCandidates(jobPost.JobID.ToString(), cd.UserID);

}


//This code runs perfectly fine

for (Int32 idx = 0; idx < candidateList.Count; idx++) // As expected candidateList has got items.

{

    Tuple<Candidate, Boolean> cand = candidateList[idx]; // Here cand has got values good to be used further. 

    Candidate cd = cand.Item1;

    if (cd.IsShortlisted)

       InsertShortCandidates(jobPost.JobID.ToString(), cd.UserID, cd.MatchingScore.ToString());

    else

       RemoveShortCandidates(jobPost.JobID.ToString(), cd.UserID);

}

慕田峪9158850
浏览 162回答 1
1回答

九州编程

您可以通过这种方式轻松遍历 Tuple,假设我有一个类班级&nbsp; public class MyClass&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int Counter { get; set; }&nbsp; &nbsp; }元组列表&nbsp;List<Tuple<MyClass, bool>> listoftuple = new List<Tuple<MyClass, bool>>();设置元组列表&nbsp; for (int i = 0; i <=10; i++)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; MyClass cls = new MyClass();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cls.Counter = i;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Tuple<MyClass, bool> tuple =&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; new Tuple<MyClass, bool>(cls, true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; listoftuple.Add(tuple);&nbsp; &nbsp; &nbsp; &nbsp; }获取元组值&nbsp;foreach (Tuple<MyClass, bool> item in listoftuple)&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Tuple<MyClass, bool> gettuple = item;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(gettuple.Item1.Counter);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Console.WriteLine(gettuple.Item2);&nbsp; &nbsp; &nbsp; &nbsp; }你的代码有问题您代码中的问题是 foreach 循环的第一行候选 cd = cand.Item1;尝试替换为Tuple<Candidate, Boolean> cd = cand然后Candidate candidate = cd.Item1
随时随地看视频慕课网APP
我要回答