João Colucas
João Colucas

Reputation: 249

LINQ "OR" in expression

Just trying to get a cleaner code on a delete method. I need to delete records from a database if a certain column value matches one of two columns in another table.

Is there a better way to delete multiple records, with a "OR"-like expression, so that I can have only one for each loop instead of the following two?

public static void DeleteStageById(int StageId, int ApplicationId)
{
    using (IPEntities ip = IPEntities.New())
    {
        var stage = ip.mkStages;
        var stageCultures = ip.appObjectCultures;
        var stageStates = ip.mkStatesInStages;

        foreach (var stageCulture in stageCultures.Where(sC => sC.ObjectCultureId == stage.Where(s => s.StageId == StageId && s.ApplicationId == ApplicationId).FirstOrDefault().OCId_Name))
        {
            stageCultures.DeleteObject(stageCulture);
        }

        foreach (var stageCulture in stageCultures.Where(sC => sC.ObjectCultureId == stage.Where(s => s.StageId == StageId && s.ApplicationId == ApplicationId).FirstOrDefault().OCId_Description))
        {
            stageCultures.DeleteObject(stageCulture);
        }

        ...

        ip.SaveChanges();
    }
}

Upvotes: 0

Views: 93

Answers (2)

fubo
fubo

Reputation: 45947

my linq would look like this one

var stage = ip.mkStages;
var stageCultures = ip.appObjectCultures;
var stageStates = ip.mkStatesInStages;

//store this result into a temp variable so it only needs to run once
var temp = stage.Where(s => s.StageId == StageId && s.ApplicationId == ApplicationId).FirstOrDefault();

if (temp != null)
{
    foreach (var stageCulture in stageCultures.Where(sC => sC.ObjectCultureId == temp.OCId_Name || sC.ObjectCultureId == temp.OCId_Description))
    {
        stageCultures.DeleteObject(stageCulture);
    }                     
    ...
    ip.SaveChanges();
}

Upvotes: 4

Binkan Salaryman
Binkan Salaryman

Reputation: 3048

I recommend avoiding confusing expressions, but here you go:

foreach (var stageCulture in stageCultures.Where(sC => {
        var v = stage.Where(s => s.StageId == StageId && s.ApplicationId == ApplicationId).FirstOrDefault();
        return sC.ObjectCultureId == v.OCId_Name || sC.ObjectCultureId == v.OCId_Description;
    })
{
    stageCultures.DeleteObject(stageCulture);
}

Upvotes: 1

Related Questions