这在我看来更像是一个 SQL 问题,所以我会相应地回答它。如果您不是在寻找基于 SQL 的答案,请在问题中更清楚。如果你是,请修改你的标签。
只要类型的数量是固定的并且已知的,下面的 SQL 就可以构成你的底层 SQL 查询(假设源是一个 SQL 数据库):
SELECT a.StaffID, Name,
CASE WHEN b.ID IS NOT NULL THEN 1 ELSE 0 END AS Type1,
CASE WHEN c.ID IS NOT NULL THEN 1 ELSE 0 END AS Type2,
CASE WHEN d.ID IS NOT NULL THEN 1 ELSE 0 END AS Type3
FROM dbo.Staff a
LEFT JOIN dbo.StaffType b ON a.StaffID = b.StaffID AND b.TypeID = 1
LEFT JOIN dbo.StaffType c ON a.StaffID = c.StaffID AND c.TypeID = 2
LEFT JOIN dbo.StaffType d ON a.StaffID = d.StaffID AND d.TypeID = 3
在您的 GridView 中,每个复选框都会知道它的 StaffID(从行)和 TypeID(从列),所以只需处理它的 OnChanged 事件并调用类似的东西:
DECLARE @StaffID INT = 1, @TypeID INT = 1
IF EXISTS (SELECT * FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID)
DELETE FROM dbo.StaffType WHERE StaffID = @StaffID AND TypeID = @TypeID
ELSE
INSERT INTO dbo.StaffType ( StaffID, TypeID )
VALUES ( @StaffID, @TypeID )
更新了 LINQ 版本:
var q2 =
from staff in staffList
from type1 in typesList
.Where(t => t.StaffID == staff.StaffID && t.TypeID == 1)
.DefaultIfEmpty()
from type2 in typesList
.Where(t => t.StaffID == staff.StaffID && t.TypeID == 2)
.DefaultIfEmpty()
from type3 in typesList
.Where(t => t.StaffID == staff.StaffID && t.TypeID == 3)
.DefaultIfEmpty()
select new
{
StaffID = staff.StaffID,
Name = staff.Name,
Type1 = (type1 != null),
Type2 = (type2 != null),
Type3 = (type3 != null)
};