I have a list of projects with a list of project members for each project as follows
public List<Project> Projects { get; set; }
public class Project
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public List<Member> Members { get; set; }
}
public class Member{
public Guid Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
I want to select projects for a list of member Ids using LINQ, thank you!
CodePudding user response:
I want to select projects for a list of member Ids using LINQ
List<Guid> memberIdlist = ... // fill
You can use Intersect...Any
IEnumerable<Project> projectsOfMembers = Projects
.Where(p => p.Members.Select(m => m.Id).Intersect(memberIdlist).Any());
This is an efficient approach if this list can get large, since Intersect is a set based appoach and Any stops at the first true. If it's small you could also use:
IEnumerable<Project> projectsOfMembers = Projects
.Where(p => p.Members.Any(m => memberIdlist.Contains(m.Id)));
I suggest to not use a List<Guid> but a HashSet<Guid>. Then you can use Overlaps:
IEnumerable<Project> projectsOfMembers = Projects
.Where(p => memberIdSet.Overlaps(p.Members.Select(m => m.Id)));
CodePudding user response:
If you have a list of Guids, you can check against it by using .Contains() inside .Where():
var projects = new List<Project>();
//Add projects
var memberIds = new List<Guid>();
//Add member IDs
var memberProjects = projects
.Where(p => p.Members.Any(m => memberIds.Contains(m.Id)));
CodePudding user response:
try something like this:
var projects = new List<Project>();
List<Guid>searched_value = new List<Guid>();
var newList = projects.Where(p => p.Members.Any(m => searched_value.Any(s => s == m.Id))).ToList();
Edited to reflect the OP wants to check against a List
