-1

I tried to use Except method. I thought this method was more powerfull and generates a cleaner SQL than a WHERE clause but not. It generates the same sql.

So why / when use Except method ?

EDIT : here is a sample :

// Get customers except those which ID are in the LostCustomers table
TblCustomers.Except(TblCustomers.Where(tj => LostCustomers.Select(lj => lj.CustomerId).Contains(tj.CustomerID))).Select(j => new
{
    CustomerId = j.CustomerID,
    CustomerRef = j.CustomerRef,
    CustomerName = j.Name
})

// Get customers except those which ID are in the LostCustomers table
TblCustomers.Where(tj => !LostCustomers.Select(lj => lj.CustomerId).Contains(tj.CustomerID)).Select(j => new
{
    CustomerId = j.CustomerID,
    CustomerRef = j.CustomerRef,
    CustomerName = j.Name
})

Thx

Florian
  • 4,507
  • 10
  • 53
  • 73

1 Answers1

0

It's rarely worthwhile to choose a LINQ pattern based on what SQL you think it will produce. Instead, use whichever method seems to give you the clearest code. For example, I would consider Except to be clearer in this case:

var taskIds = db.Tasks.Select(task => task.Id);
var doneTaskIds = db.TaskCompletions.Select(tc => tc.TaskId);

var unfinishedTaskIds = taskIds.Except(doneTaskIds);

as opposed to:

var unfinishedTaskIds = taskIds.Where(id => !doneTaskIds.Contains(id));

But there are many, many cases where Where() makes more sense. Chances are, in the example above, you could just say this, which would be even clearer:

var unfinishedTasks = db.Tasks.Where(task => !task.TaskCompletions.Any());
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315