I am having two lists as follows:
List<string> l1 = new List<string>( new string[]{
"United States",
"Brazil",
"India",
"Canada"
});
List<string> l2 = new List<string>( new string[]{
"Asia:India",
" North America:Canada",
"EU:Germany"
}) ;
how to list all items from l2 in which contains the string in l1 using Linq Lambda?
Desired Output
"Asia:India"
"North America:Canada"
For each item in the second list, check if there is any item in the first list that is part of the item:
l2.Where(i => l1.Any(j => i.Contains(j));
Note that this can be slow for large lists.
If you have a lot of countries to look for, I suggest using HashSet<string> (it has better Contains time compexity, O(1) vs O(N)):
HashSet<string> countries = new HashSet<string>() {
"United States",
"Brazil",
"India",
"Canada",
};
To create countries from l1:
HashSet<string> countries = new HashSet<string>(l1);
Then you can put a simple Linq:
var result = l2
.Where(item => countries.Contains(item.Substring(item.IndexOf(':') + 1)));
You data has inner structure: Area:Country which we can exploit with a help of Substring and IndexOf
Demo:
var l1 = new List<string>() {
"United States",
"Brazil",
"India",
"Canada",
"Congo", // <- My special test case
};
var l2 = new List<string>() {
"Asia:India",
"North America:Canada",
"EU:Germany",
"Africa:Democratic Republic of Congo"
};
HashSet<string> countries = new HashSet<string>(l1);
var result = l2
.Where(item => countries.Contains(item.Substring(item.IndexOf(':') + 1)));
Console.Write(string.Join("; ", result));
Outcome:
Asia:India; North America:Canada
Note abscence of unwanted Africa:Democratic Republic of Congo: Congo and Democratic Republic of Congo are different states.
Edit: Linq Join solution
var result = l2.Join(
l1,
item => item.Substring(item.IndexOf(':') + 1),
item => item,
(left, right) => left);