Multiple foreach for multiple list data

我的梦境 提交于 2021-02-05 05:52:40

问题


I have 2 string list.

var justiceCourtName = formCollection["JusticeCourtName"];
var courtId = formCollection["CourtID"];
var justiceCourtNameList = justiceCourtName.Split(',');
var courtIdList = courtId.ToList();

justiceCourtNameList values below:

"New York"

"Paris"

courtIdList values below:

"10.33"

"43.15"

My question:

I need to use foreach for justiceCourtNameList and courtIdList after that , from justiceCourtNameList to Name (below) and from courtIdList to lawCourtId one by one.

But I do not know how can i set justiceCourtNameList and courtIdList one by one to new LawCourt ?

var lawCourt = new LawCourt { JusticeCourtID = lawCourtId, Name = lawCourtName };


ServiceLibraryHelper.LawServiceHelper.UpdateLawCourt(lawCourt); // Update

回答1:


If I understood your question correctly, what you want is the Zip extension method:

var results = courtIdList
                  .Zip(justiceCourtNameList,
                       (lawCourtId, lawCourtName) =>
                           new LawCourt
                           {
                               JusticeCourtID = lawCourtId,
                               Name = lawCourtName
                           )};

It enumerates the lists in parallel, and associates the current item from the first list with the current item from the second. The lambda expression specifies what to return in the output sequence, based on the pair of items from the input sequences.




回答2:


It might be Enumerable.Zip can serve your purpose (MSDN link):

int[] numbers = { 1, 2, 3, 4 };
string[] words = { "one", "two", "three" };

var numbersAndWords = numbers.Zip(words, (first, second) => first + " " + second);

foreach (var item in numbersAndWords)
    Console.WriteLine(item);

// This code produces the following output:

// 1 one
// 2 two
// 3 three



回答3:


Don't use foreach operator but the for operator. Check before that both arrays have equal length.

List<string> justiceCourtNameList = ...
List<double> courtIdList = ...

if(justiceCourtNameList.Count != courtIdList.Count) {
    throw new ArgumentException("justiceCourtNameList and courtIdList must have the same length");
}

for(int i=0; i<justiceCourtNameList.Count; i++) {

    string justiceCourtName = justiceCourtNameList[i];
    double courtId = courtIdList[i];

    // DO HERE WHATEVER YOU WANT HERE
}

Double synchronous iteration with foreach is not possible.



来源:https://stackoverflow.com/questions/24403147/multiple-foreach-for-multiple-list-data

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!