sprocket12
sprocket12

Reputation: 5488

How to Join two Entities and Get Unique Rows from One

I have 2 entities A and B, each one has a field Number, I need to get all rows from entity A where the Number does not exist in B.

Any ideas? Does it need a join?

Upvotes: 0

Views: 98

Answers (3)

Björn
Björn

Reputation: 3418

As you are not giving very much information it's hard to tell. But maybe you could do something like this:

public class TestEntity
{
    public int Number { get; set; }
    public TestEntity(int num)
    {
        Number = num;
    }
}

public void WriteResult()
{
    List<TestEntity> lstA = new List<TestEntity>();
    List<TestEntity> lstB = new List<TestEntity>();
    for (int i = 0; i < 10; i++)
    {
         lstA.Add(new TestEntity(i));
         lstB.Add(new TestEntity(i+4));
    }

    List<TestEntity> result = lstA.FindAll(teA => !lstB.Any(teB => teA.Number == teB.Number)); //This will give you all entities in lstA that does not have any equals in lstB
    foreach (var item in result)
    {
         Console.WriteLine(item.Number);
    }
}

Upvotes: 0

Rohan B&#252;chner
Rohan B&#252;chner

Reputation: 5393

very crude, but you can do it without a join like this

var listB = b.Select(o => o.Number).Distinct();

var result = a.Where(o => !listB.Contains(o.Number));

Upvotes: 0

Joanna Derks
Joanna Derks

Reputation: 4063

Will that do the trick ?

  var result = entityA.Where(a => !entityB.Any(b => a.Number == b.Number))

Upvotes: 3

Related Questions