问题
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