Rossman
Rossman

Reputation: 43

Exclude list of complex objects from IQueryable by two properties

I have two types:

public class DocumentEntityItem 
{
    public int Id { get; set; }
    public string Type { get; set; }
}

public partial class DocumentEntityToFilesCategory
{
    public int FilesCategoryId { get; set; }
    public int CmsFileId { get; set; }
    public Nullable<int> Sorder { get; set; }
    public string DocumentType { get; set; }

    public virtual FilesCategory FilesCategory { get; set; }
}

And I got the list of DocumentEntityToFilesCategory type. I want to exclude from this list another list of type DocumentEntityItem by two properties - CmsFileId and DocumentType, so I tried to write some code like:

List<string> mainList  = new List<string>()
{
   "1/document",
   "1/link",
   "2/document",
   "3/link"
};
    var documentToCategoryItems= DB.DocumentEntityToFilesCategory.Where(z => z.FilesCategoryId == categoryId);
    List<DocumentEntityItem> documentEntityItems= mainList.Select(z => new DocumentEntityItem
    {
       Id = Int32.Parse(z.Split("/")[0]),
       Type = z.Split("/")[1]
    }).ToList();
    var toDelete = documentToCategoryItems.Where(z => !documentEntityItems.Any(c=>c.Id==z.CmsFileId&&c.Type==z.DocumentType));

But, List.Any() supports only primitive types.

Upvotes: 2

Views: 205

Answers (1)

Blindy
Blindy

Reputation: 67380

I'll start by saying that your conclusion is flat out wrong, and the error message you mentioned in your comments either does not exist or is related to something completely different. Here's a fiddle showing your code compile as written without any problems: https://dotnetfiddle.net/Aor3rH

You should probably know however that even if it does compile, the quality of the code is extremely low, because you're doing an O(n^2) algorithm to implement your exclude (difference) operation, instead of an O(nlogn) operation as you should be able to trivially do. Also this specific algorithm is part of the morelinq nuget package under the name ExceptBy, so you don't even need to implement it correctly, just reference it and use it!

Upvotes: 3

Related Questions