例如,你可以使用LINQ和幫助方法的匹配條件:
bool IsTargetFile(UploadedFile file, int documentId)
{
bool isTargetId = file.EntityId == documentId;
bool isTargetName = file.EntityName == "Document";
bool isActive = file.IsActive;
return isTargetId && isTargetName && isActive;
}
void Main()
{
var document = new Document { Id = 1, Name = "MyDocument" };
var targetFile1 = new UploadedFile { EntityId = 1, EntityName = "Document", IsActive = true };
var nonTargetFile1 = new UploadedFile { EntityId = 2, EntityName = "Document", IsActive = true };
var nonTargetFile2 = new UploadedFile { EntityId = 1, EntityName = "WrongDocument", IsActive = true };
var nonTargetFile3 = new UploadedFile { EntityId = 1, EntityName = "Document", IsActive = false };
document.UploadedFiles = new List<UploadedFile>
{
targetFile1, nonTargetFile1, nonTargetFile2, nonTargetFile3
};
var targetFiles = document.UploadedFiles.Where(file => IsTargetFile(file, document.Id));
foreach (var file in targetFiles)
Console.WriteLine("{0} {1} {2}", file.EntityId, file.EntityName, file.IsActive);
}
幫助類:
public class Document
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<UploadedFile> UploadedFiles { get; set; }
}
public class UploadedFile
{
public int Id { get; set; }
public string FileName { get; set; }
public string EntityName { get; set; }
public int EntityId { get; set; }
public bool IsActive { get; set; }
}
這意味着,document.UploadedFiles有所有的記錄,不僅僅是滿足我提到的條件。你的答案就像是加載UploadedFile中的所有記錄,然後再次過濾它們。這不是我要找的。 – 2015-02-12 06:28:51