Home > OS >  LINQ how to select ID that exists in one list but not exist in the other
LINQ how to select ID that exists in one list but not exist in the other

Time:02-15

I have two models like this:

public class Process
{
        public int Id { get; set; }
        public int PaletID { get; set; }
        public Paleta Palet { get; set; }
        public DateTime Start { get; set; }
        public DateTime? End { get; set; }
}

public class Palet
    {
        public int Id { get; set; }     
        public int DeliveryNoteID { get; set; }          
        public DateTime Date { get; set; }
        public string Type { get; set; }
        public int Length { get; set; }
        public int Width { get; set; }
        public int Height { get; set; }
        public int? Nrpcs { get; set; }
        public double Volume { get; private set; }                       
        public Status Status { get; set; }        
        public DeliveryNote DeliveryNote { get; set; }        
    }

What I need to do is select (for autocomplete), Ids that exist in Palet, but do not exist in Process.

How can I do this?

CodePudding user response:

What I need to do is select (for autocomplete), Ids that exist in Palet, but do not exist in Process.

listOfPalet.Select(p => p.Id).Except(listOfProcess.Select(p => p.Id))

Note that the operation will also deduplicate the list of Palet IDs. The output is a list of just the IDs. If you want the whole Palet object, let me know and I'll make a revision

CodePudding user response:

Sounds like a job for .GroupJoin(). Maybe something like this:

IReadOnlyList<Palet> palets = LoadPalets();
IReadOnlyList<Process> processes = LoadProcesses();

var paletsWithoutProcess = palets
    .GroupJoin(
        processes,
        palet => palet.Id,
        process => process.PaletId,
        (palet, processes) => processes.Any() ? null : palet)
    .Where(palet => palet != null)
    .ToList();
  • Related