[C#]LINQ 表达式中的"或"

标签: Linq C#
发布时间: 2017/2/27 4:18:37
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

只想要一个更干净的代码删除方法。我需要从数据库中删除记录,如果某列的值与另一个表中的两个列中的一个相匹配。

有更好的方式来删除多个记录,与"或"类似的表达式,所以,我只可以有一个 for each 循环而不是以下两个吗?

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();
    }
}

解决方法 1:

我 linq 将看起来像这一个

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();
}
赞助商