1

I have two list, I want the values of list 1 if it contains any of value from list 2.

List<string> list1 = new List<string>();
list1.Add("Sunday is far away");
list1.Add("Today is Monday");
list1.Add("Tuesday is too near");

List<string> list2 = new List<string>();
list2.Add("Sunday");
list2.Add("Monday");
list2.Add("Tuesday");

var result1 = list1.Where(x => list2.Any(y => y.Contains(x))).ToList(); //no results
var result2 = list2.Where(x => list1.Any(y => y.Contains(x))).ToList(); //give values of list2. But I need values of list1

Update:

I need values of list1 in result, how can I get that?

2
  • 1
    so what is the problem here? Commented Nov 8, 2017 at 11:56
  • 1
    In first approach you messed up x and y. Should be Any(y => x.Contains(y)) Commented Nov 8, 2017 at 11:58

2 Answers 2

1

Simple thing you missed, Take a look into the collection, All Items in the first list are larger than that of second, so the contains will return false. So you have to check for second item in first like the following:

Here is your modified code with result:

var result1 = list1.Where(x => list2.Any(y => x.Contains(y))).ToList(); 
var result2 = list2.Where(x => list1.Any(y => y.Contains(x))).ToList(); 
Sign up to request clarification or add additional context in comments.

Comments

0

Simply you can. If List1 contains any value of List2 then result=List1. Otherwise null;

var result = list2.Any(l2 => list1.Contains(l2))==true?list1:null;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.