How to compare the string elements of two lists without for each?

I have two lists and want to compare the elements, and want to extract matching elements. The problem is, the matching doesn’t have to be the whole string, but only the part of it.

ListA: {“ID12”, “ID13”, “ID15”, “ID17”, “ID18”}
ListB: {“Special11”, “Special13”, “Special15”, “Special19” }

In this case, I want the result list to contain:

ListMatches: {“ID13”, “ID15”}

because the numbers matched. Both elements are out of order, so we cannot just compare the elements of same index numbers. Also, I don’t want to trim "ID"s or “Special” and store them into another list or array to make the comparison easier. I just want to use these arrays as it is. I tried something like

listA.Select(Function (x) x.Substring(2, 2) == listB.(/not sure what to put in here/))

I cannot do listB(x).Substring(7, 2) because we have to check all elements in the list, but not of the same index. How could I do this using Lambda?

Give a try to LINQ
play around with the intersect function
egalize both list to the common compair value (I guess in your case the numbers)

Another approach would be to realize it by a Join statement and pickup with select the matching ListA values

I was actually looking at Except and Intersect, but I don’t think I could use them… as I have to specify the substring.

i will try give me some minutes

@tomato25

(From l1 In ListA
Join l2 In ListB
On l1.Substring(2, 2) Equals l2.Substring(7, 2)
Select l1).toList

3 Likes

I am trying to understand your code, but I am confused with “Join”.
Isn’t Join supposed to be used to concatenate elements of an array/list?

How could Join be used in this scenario?

and it does work! I tested it with multiple cases, but it worked and retrieved the matching elements. Could you please help me understand how “Join” is used in this case because this case seems to be irrelevant to concatenation.

Join coming from Linq and is different from String.Join

Join.

This is a keyword in LINQ. As with other query languages (such as SQL) joining matches every element in two collections based on some condition.

1 Like

I now understand… I was thinking about string.join this whole time… Thanks!

Ok great its working. So just flag the solution that other members can benefit from it

For your further readings may following helps:
https://linqsamples.com/

1 Like

This topic was automatically closed 3 days after the last reply. New replies are no longer allowed.