首页 > 解决方案 > 如何检查记录是否存在于一个表中,那么它应该在 C# 中忽略它

问题描述

我在sql中有两个表如下

分支机构

ID   | BranchID | GameTypeID | flag
1    | 55       | 111        | 1
2    | 16       | 235        | 0

游戏

GameTypeID
123
456
111
235
458

我想要实现的是,当加载游戏时,它必须检查 GameTypeID 是否存在于该 ID 的分支表中并且标志是否为 1。例如,如果我通过 BranchId 55,那么从游戏列表中 gametypeid 111 应该是删除给我以下列表

Expected Outcome
    Games
    235
    123
    456
    458

这是我的代码

GameLevel retVal = new GameLevel(GetGames(gameid, isdateroot, startdate, enddate, iscurrent, isdatesort, requestfrom));
var assignments =GetByBranchId(SessionManager.LoggedBranch.BranchIDb => b.Flag);
if (assignments.Any())
{
    var gameTypes = assignments.Select(x => x.GameTypeId.ToString()).ToList();
    retVal.Rows = retVal.Rows.Where(x => gameTypes.Contains(x.GameTypeID)).ToList();
}
return retVal;

所以上面发生的事情是,当它通过 BranchID 55 时,它会继续检查标志,但问题是当它发现该行时它没有忽略 GametypeID 111 它会忽略其他所有内容,这就是我回来的结果

*current output*
Games
111

我的代码有什么问题?

标签: c#sql-server

解决方案


我想我看到了这个问题。我将在这里浏览您的代码,如果我做出错误的假设,您可以纠正我的

//1. This line gets an instance of a List<Games> (or something roughly like that)
GameLevel retVal = new GameLevel(GetGames(gameid, isdateroot, startdate, enddate, iscurrent, isdatesort, requestfrom));
//2. This line gets the GameTypeIds for the flagged Branch
var assignments =GetByBranchId(SessionManager.LoggedBranch.BranchIDb => b.Flag);
//3. self explanatory. 'If there is anything in the assignment variable'
if (assignments.Any())
{
    //4. Get a list of GameTypeId values from assignments
    var gameTypes = assignments.Select(x => x.GameTypeId.ToString()).ToList();

    //5. Here's where I think you went wrong
    //5. This line gets the Games where gameTypes contains the GameTypeId in retVal.
    retVal.Rows = retVal.Rows.Where(x => gameTypes.Contains(x.GameTypeID)).ToList();
}
return retVal;

您想要的是 'retVal' 中不包含在 'gameTypes.GameTypeId' 中的所有游戏,而您实际返回的是相反的。您将返回 'retVal' 中在 'gameTypes' 中具有匹配 GameTypeId 的所有游戏

所以......你需要做的就是与你目前正在做的相反改变这条线

retVal.Rows = retVal.Rows.Where(x => gameTypes.Contains(x.GameTypeID)).ToList();

进入这个

retVal.Rows = retVal.Rows.Where(x => !gameTypes.Contains(x.GameTypeID)).ToList();

我所做的只是添加“not”运算符,现在您返回的游戏与标记的 GameTypeId 不匹配


推荐阅读