提问人:BlackCat 提问时间:10/26/2023 更新时间:10/26/2023 访问量:40
如何修改linq排除部分记录?
How to modify linq to exclude some records?
问:
对于下面的 Linq,我想修改它以排除一些记录。 以下是现有的:
public partial class AuditLog
{
public AuditLog()
{
this.AuditLogDetail = new HashSet<AuditLogDetail>();
}
public string IdAuditLog { get; set; }
public int IdUser { get; set; }
public string Changeset { get; set; }
public System.DateTime AuditDateTime { get; set; }
public int AuditAction { get; set; }
public string TableName { get; set; }
public int IdRecord { get; set; }
public string IpAddress { get; set; }
public bool IsSystem { get; set; }
public string Description { get; set; }
public virtual User User { get; set; }
public virtual ICollection<AuditLogDetail> AuditLogDetail { get; set; }
}
public partial class AuditLogDetail
{
public string IdAuditLogDetail { get; set; }
public string IdAuditLog { get; set; }
public string ColumnName { get; set; }
public string OriginalValue { get; set; }
public string NewValue { get; set; }
public virtual AuditLog AuditLog { get; set; }
}
AuditLogs = groupedLog.Where(p => p.AuditLogDetail.Any(q =>
!string.IsNullOrWhiteSpace(q.OriginalValue) ||
!string.IsNullOrWhiteSpace(q.NewValue)))
.OrderBy(p => p.AuditDateTime)
.Select(p => new DtoAuditLog
{
TableName = p.TableName,
AuditAction = p.AuditAction,
Details = p.AuditLogDetail.Where(q => !string.IsNullOrWhiteSpace(q.OriginalValue) ||
!string.IsNullOrWhiteSpace(q.NewValue))
.Select(q => new DtoAuditDetail
{
ColumnName = q.ColumnName,
OriginalValue = q.OriginalValue,
NewValue = q.NewValue
}).ToList()
}).ToList()
我想从某些 Audit.Table 中排除某些列或从某些 Audit.Table 中排除所有列。为此,我使用了以下代码,其中将表和列保留在列表中,但是当提到特定列时,它可以排除。但是,当我提到列表中没有列时,并没有排除。
List<(string TableName, List<string> Columns)> excludedColumns = new List<(string TableName, List<string> Columns)>
{
("Table1", new List<string> { "Column1", "Column2" }), // Exclude Column1 and Column2 of Table1
("Table2", new List<string>()) // Exclude all columns of Table2
};
AuditLogs = groupedLog
.Where(p => p.AuditLogDetail.Any(q =>
!string.IsNullOrWhiteSpace(q.OriginalValue) || !string.IsNullOrWhiteSpace(q.NewValue)))
.OrderBy(p => p.AuditDateTime)
.Select(p => new DtoAuditLog
{
TableName = p.TableName,
AuditAction = p.AuditAction,
Details = p.AuditLogDetail
.Where(q => !string.IsNullOrWhiteSpace(q.OriginalValue) || !string.IsNullOrWhiteSpace(q.NewValue))
.Where(q =>
{
var excludedColumnsForTable = excludedColumns.FirstOrDefault(ec => ec.TableName == p.TableName);
if (excludedColumnsForTable != default((string, List<string>)))
{
// Check if the current column should be excluded for this table
return !excludedColumnsForTable.Columns.Contains(q.ColumnName);
}
return true; // Include the column if it's not specified in the exclusion list
})
.Select(q => new DtoAuditDetail
{
ColumnName = q.ColumnName,
OriginalValue = q.OriginalValue,
NewValue = q.NewValue
}).ToList()
}).ToList();
答: 暂无答案
评论
ColumnName
return
Where
excludedColumnsForTable.Columns.Count > 0 &&