0

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)));
4
  • 1
    why not Semester{5,{2,4}} in the result? Commented Aug 19, 2020 at 6:32
  • I agree with @SowmyadharGourishetty, there isn't an explanation on why inputs {1, 2} retrieves parentids only containing 1 but not parentids that only contain 2. Commented Aug 19, 2020 at 7:21
  • @Hayden, I later saw the title LINQ select List where sub-list all items contains another list it says all items that match the parentId's Commented Aug 19, 2020 at 7:23
  • @SowmyadharGourishetty Thanks for pointing that out, just not clear in the question itself. Commented Aug 19, 2020 at 7:24

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

6 Comments

If you want to include the list if it atleast has any one of the parentId's, you can use Any instead of All in the above Linq
Thanks, when i use this , find all items that contains id but i want to select items that every item list in list.
@ar.gorgin Yes, this works in the same way. can you please check the working code attached
You are almost there, instead of m.Parents.Any try m.Parents.All. Which I have already mentioned in my answer. please check my answer again
i use All , this return items like Any and item with this id.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.