简体   繁体   中英

LINQ select List where sub-list all items contains another list

I have a model with list items.

public class Semester{
    public int Id { get; set; }
    public List<SemesterParent> Parents { get; set; }
}

public class SemesterParent{
    public int Id { get; set; }
    public int SemesterId { get; set; }
    public int ParentId { get; set; }
}

I have a list<int> of parentids . I want to get semester list that Parents in parentids list.

For example

Semester{1,{}}
Semester{2,{}}
Semester{3,{1,2}}
Semester{4,{1}}
Semester{5,{2,4}}

When I have ParentIdes {1,2} the result is:

Semester{3,{1,2}}
Semester{4,{1}}

I use this code.

var parentIds =
            await _semesterTermStudentService.Select(m => m.IsAccept && m.StudentId == student.Id);
var semester=await _semesterService.FindAsync(m=>
             m.Parents.Any(y => parentIds.Contains(y.ParentId)));

You can do as below. Here is the working code

List<Semester> s = new List<Semester>();
var parentIds = new List<int> { 1, 2 };
var result = s.Where(x => x.Parents != null && x.Parents.Any() && x.Parents.All(y => parentIds.Contains(y.Id))).ToList();

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