Question

I have two lists, one have a list of object A an other a list of objects B, like this:

ObjectA
{
    Int64 idObjectA;
    String name;
    ....
}

ObjectB
{
    Int64 idObjectB;
    Int64 idObjectA;
    String name;
    ....
}

I have two list, one with Object A and other with Object B. I want to create a new list C that have only objects B, which IDObjectA is any ID of the list A.

In SQL it would be somthing line that:

select * from B where IDObjectA IN(1,2,3,4...);

In my case, the list of values for the IN clause is the list of ObjectA, which have the property idObjectA.

Was it helpful?

Solution 2

The same with Join and without Contains:

var listC = listB.Join(listA, b => b.ObjectAId, a => a.Id, (b, a) => b).ToList();

OTHER TIPS

You can use the Join linq method to achieve this by joining listB and listA by their idObjectA, then select itemB.

var result = (from itemB in listB
              join itemA in listA on itemB.idObjectA equals itemA.idObjectA
              select itemB).ToList();

This method has a linear complexity (O(n)). Using Where(... => ....Contains()) or double foreach has a quadratic complexity (O(n^2)).

This is slightly different way of doing it as opposed to a join.

List<ObjectA> listA = ..
List<ObjectB> listB = ..
int[] listAIds = listA.Select(a => a.idObjectA).ToList();
               //^^ this projects the list of objects into a list of ints

//It reads like this...

//get items in listB WHERE..
listB.Where(b => listAIds.Contains(b.idObjectA)).ToList();
//b.idObjectA is in listA, OR where listA contains b.idObjectA

Not linq, but does what you want it to:

List<ObjectB> C = new List<ObjectB>();
foreach (n in B)
{
    foreach (c in A)
    {
        if (n.idObjectA == c.idObjectA)
        {
            C.Add(n)
            break;
        }
    }
}

Or if you wanted higher performance, use a for, and higher than that use Cédric Bignon's solution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top