简体   繁体   中英

Linq: select objects where list contains properties that must be in another list

I've read many solutions using linq and lists, but I can't seem to find a solution to my issue. I've described the situation below. The list of Details includes every detail in the system.

List<Detail> allDetails

Detail
    List<Program> programs

Program
    int ID
    int code

I have a list of program IDs a specific role has access to.

int[] specificPrograms

The requirement is that I need to return a list of Details from allDetails where the list of programs for a Detail in allDetails must all be contained in specificPrograms list.

For example: If there are 2 details containing the following programs

Detail 1
Programs   ID        Code
---------------------------------
           1         111
           2         222
           3         333
           4         444

Detail 2
Programs   ID        Code
---------------------------------
           1         111
           3         333 

SpecificPrograms contains IDs: 1, 3, 4

Only Detail 2 would be returned because the programs in each detail must exist in the specificPrograms list.

var result = allDetails.Where(detail => detail
                 .programs.All(x => SpecificPrograms.Contains(x.ID)));

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM