Reputation: 499
First I want to know if at least one element in a first list can be found in a second list.
List<string> list1 = new[] { "A", "C", "F", "H", "I" };
List<string> list2 = new[] { "B", "D", "F", "G", "L" };
I am using below code to do this -
bool isFound = list1.Intersect(list2).Any();
But I want to know which element is that. Like in above case it is 'F'
What is the best way to do this?
Upvotes: 0
Views: 87
Reputation: 1466
Instead of bool variable You can take another list variable like:
List<string> list3
Variable to get list of items which are forund in second list and assign the result to list3
List<string> list3= list1.Intersect(list2).ToList();
Upvotes: 1
Reputation: 9322
Try:
List<string> list1 = new List<string> { "A", "C", "F", "H", "I" };
List<string> list2 = new List<string> { "B", "D", "F", "G", "L" };
String sel = list1.Intersect(list2).FirstOrDefault()??"";
Console.WriteLine(sel);
Try my Demo
Upvotes: 2
Reputation: 98810
You can use Enumerable.Intersect
method only, you don't need to use Any
in your case.
Produces the set intersection of two sequences.
List<string> list1 = new List<string>(){ "A", "C", "F", "H", "I" };
List<string> list2 = new List<string>(){ "B", "D", "F", "G", "L" };
var intersect = list1.Intersect(list2);
foreach (var i in intersect)
{
Console.WriteLine(i);
}
Output will be;
F
Here is a DEMO
.
Upvotes: 2
Reputation: 75316
You just use Intersect
only:
var result = list1.Intersect(list2);
Upvotes: 4