我有两个清单。想象一下:
List<string> firstList = {"ab","bb","cd","ed","fe","ff","eg","lh","di","dj"}
List<string> secondList = {"ab","fe","lh","dj"}
我需要遍历firstList并为secondList中存在的每个元素“做某事”。可能的?请注意,在这一"do something
部分中,我需要将Add
下一个元素firstList
移到另外三分之一List
。请指导。
我的工作是:
for (int g = 0; g < row_2.Count; g++)
{
for (int h = 0; h < d["topHeadings"].Count; h++)
{
if (row_2[g] == d["topHeadings"][h])
{
while ((row_2[g] != d["topHeadings"][h + 1]))
{
row_2_1.Add(row_2[g + 1]);
g++;
}
}
}
}
您可以使用All
和执行此操作Contains
:
bool allInFirst = secondList.All(entry => firstList.Contains(entry));
这是true
如果所有的元素secondList
也包含在firstList
。
根据您的评论,您想要的东西与您的问题所要求的完全不同。似乎您想遍历firstList
并为中存在的每个元素“做某事” secondList
,因此您可以执行以下操作:
foreach(var element in firstList.Where(secondList.Contains))
// do something with element
这将过滤firstList
存在于secondList
其中的元素并对其进行迭代。也许我再次误解了您,而您又想反过来,只需要交换firstList
和即可secondList
。
如果您需要索引,也许最好的方法是这样的:
for (int firstIndex = 0; firstIndex < firstList.Count; firstIndex++)
{
int secondIndex = secondList.IndexOf(firstList[firstIndex]);
if (secondIndex < 0) continue;
// do what you need with firstList[firstIndex] and the indices
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句