Three basic examples. The first uses a simple nested foreach:
foreach(var item1 in list1)
foreach(var item2 in list2)
if(item1.text == item2)
{
//Do your thing
{
You could reduce nesting by using LINQ. Note that you could make this considerably fancier in LINQ (you can join lists), but I've chosen a simpelr example to show you the basic idea.
foreach(var item1 in list1)
{
var matchesInList2 = list2.Where(item2 => item1.text == item2);
foreach(var match in matchesInList2)
{
//Do your thing
}
}
There is a simpler way to approach it:
var matches = list1.Where(item1 => list2.Contains(item1.text));
foreach(var item1 in matches)
{
//Do your thing, e.g.:
//var theTextValue = item1.text;
}
To explain this simpler approach: we immediately filter list1
, and only keep the elements whose .text
value exists in list2
.
After that, it is simply a matter of looping over the found matches, you don't need to filter anymore.