I have an List containting (among other things) Remark1, Remark2 and Remark3. I'd like to make sure that only valid remarks are written in these fields. Today I check it like this:
foreach (GradeRow row in Grade.GradeRows)
{
if (!(okRemarks.Contains(row.Remark1) && okRemarks.Contains(row.Remark2) && okRemarks.Contains(row.Remark3)))
{
FailedCourseCodes.Add(row.CourseCode);
}
}
Is there a Linq expression that can do something like .Contains(List)?
You still have to check each field individually but you can eliminate the loop:
FailedCourseCodes.Add(
Grade.GradeRows.Where(row=>
okRemarks.Contains(row.Remark1) &&
okRemarks.Contains(row.Remark2) &&
okRemarks.Contains(row.Remark3)
)
);
You could make it slightly shorter by creating an array from the fields:
FailedCourseCodes.Add(
Grade.GradeRows.Where(row=>
(new [] {row.Remark1, row.Remark2, row.Remark3})
.Except(okRemarks).Any()
)
);
but that's significantly harder to read in my opinion.
诸如此类的东西将返回所有包含不良备注的行:
Grade.GradeRows.Where( row => new string[]{row.Remark1, row.Remark2, Row.Remark3}.Any ( remark => !okRemarks.Any(remark)))
.Intersect( IEnumerable ) and then comparing the result's Count() is the only option I can think of. Something in the lines of:
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 got it right, but did not add the results correctly
foreach( var failedGrade in Grade.GradeRows.Where( row => !(
okRemarks.Contains(row.Remark1) &&
okRemarks.Contains(row.Remark2) &&
okRemarks.Contains(row.Remark3) ) ) )
{
FailedCourseCodes.Add(failedGrade.CourseCode);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.