我有一个包含(除其他外)Remark1,Remark2和Remark3的List。我想确保只在这些字段中写入有效的备注。今天我这样检查:
foreach (GradeRow row in Grade.GradeRows)
{
if (!(okRemarks.Contains(row.Remark1) && okRemarks.Contains(row.Remark2) && okRemarks.Contains(row.Remark3)))
{
FailedCourseCodes.Add(row.CourseCode);
}
}
Linq表达式是否可以执行类似.Contains(List)的操作?
答案 0 :(得分:5)
您仍然需要单独检查每个字段,但您可以消除循环:
FailedCourseCodes.Add(
Grade.GradeRows.Where(row=>
okRemarks.Contains(row.Remark1) &&
okRemarks.Contains(row.Remark2) &&
okRemarks.Contains(row.Remark3)
)
);
通过从字段中创建数组,可以使其缩短:
FailedCourseCodes.Add(
Grade.GradeRows.Where(row=>
(new [] {row.Remark1, row.Remark2, row.Remark3})
.Except(okRemarks).Any()
)
);
但在我看来这很难读。
答案 1 :(得分:1)
这样的内容将返回包含错误备注的所有行:
Grade.GradeRows.Where( row => new string[]{row.Remark1, row.Remark2, Row.Remark3}.Any ( remark => !okRemarks.Any(remark)))
答案 2 :(得分:0)
.Intersect(IEnumerable)然后比较结果的Count()是我能想到的唯一选择。有些东西:
foreach( var failedGrade in Grade.GradeRows
.Select( x => new String[]{ row.Remark1, row.Remark2, row.Remark3 } )
.Where( remarks => remarks.Intersect( okRemarks ).Count() < remarks.Length ) )
{
FailedCourseCodes.Add(failedGrade.CourseCode);
}
@ d-Stanley说得对,但没有正确添加结果
foreach( var failedGrade in Grade.GradeRows.Where( row => !(
okRemarks.Contains(row.Remark1) &&
okRemarks.Contains(row.Remark2) &&
okRemarks.Contains(row.Remark3) ) ) )
{
FailedCourseCodes.Add(failedGrade.CourseCode);
}