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.

Uzair Khan
  • 2,812
  • 7
  • 30
  • 48

3 Answers3

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)
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 1
    Maybe you can also explain why the OP’s approach did not work. He did use `Contain`, after all. – Lumen Jul 05 '16 at 11:48
  • 1
    @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`. – Ivan Yurchenko Jul 05 '16 at 11:51
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
juharr
  • 31,741
  • 4
  • 58
  • 93
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));