3

I have a list of numbers as shown below:

1) List<long> list1 : 101, 102, 103

And I have a list of Objects, in which one property is long:

2) List<SomeObject> list2: 
   SomeObject[0]- (long)Id : 101,
                  Name: Adam,
                  Address:xxx
   SomeObject[1]- (long)Id : 102,
                  Name: Bran,
                  Address:xxx
   SomeObject[2]- (long)Id : 109,
                  Name: Queen,
                  Address:yyy

I want to query the second list if it has Id's present in list1. Meaning I should get list containing :

SomeObject[0]  
SomeObject[1]

Tried the code below with no success:

(from t2 in list2
          where list1 .Any(t => t2.Id.Contains(t)) == true
          select t2);

Thanks in advance.

3 Answers 3

5

You can use Enumerable.Contains:

var query = from t2 in list2
            where list1.Contains(t2.Id)
            select t2;

if the values in list1 are uniqe you can also use the more efficient Join:

var query = from t2 in list2
            join t1 in list1
            on t2.Id equals t1
            select t2;

Your approach doesn't work:

where list1.Any(t => t2.Id.Contains(t)) == true

because t2.Id returns a long which has no Contains method.

If you wanted to use Any you could use this:

where list1.Any(t => t2.Id == t)
Sign up to request clarification or add additional context in comments.

2 Comments

Maybe you can also explain why the OP’s approach did not work. He did use Contain, after all.
@TimSchmelter t is also a long but he doesn't check Id for t. He checks Id for t2 that is SomeObject which has Id.
1

The issue with your query is that you are trying to call Contains on a long. Instead it should have been list1 .Any(t => t2.Id == t). But instead you can just do a join.

from t1 in list1
join t2 in list2 on t1 equals t2.Id
select t2

Comments

1

You can also use the below code snippet to get the desired result, where

var result = list2.Where(l2 => list1.Any(l1 => l1 == l2.Id));

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.