Reputation: 109
Please help me to build a LINQ query.
I have a list List<SingleEntryReportCardModel> singleEntryReportCardModel
which contains EmployeeList
internally.
I want to have all such single entry reports which matches to the employee name as input.
I have tried doing this
singleEntryReportCardModel =
singleEntryReportCardModel
.Where(x => x.EmployeeList.Select(y => y.EmployeeName.Contains(Name)))
.ToList<SingleEntryReportCardModel>();
but throws me a type casting error
This is how it looks like:
public class SingleEntryReportCardModel
{
public GoalReportCard GoalReportCard { get; set; }
public GoalTemplateModel GoalTemplate { get; set; }
public List<EmployeeInfoModel> EmployeeList { get; set; }
}
Upvotes: 0
Views: 98
Reputation: 42377
I'm not sure what the exact problem is, but the following line looks wrong:
.Where(x => x.EmployeeList.Select(y => y.EmployeeName.Contains(Name)))
The result of your Select
will be an IEnumerable<bool>
. I don't think that's even a valid argument to Where
, but I might be wrong. It doesn't make sense to me to say "I want all elements where some collection of bool
s".
Perhaps you want this:
.Where(x => x.EmployeeList.Any(y => y.EmployeeName.Contains(Name)))
Also, once you get it working, you should be able to remove the generic type argument from your call to ToList
:
.ToList();
Upvotes: 4
Reputation: 4001
This LINQ will extract all the elements on which the Employee List contains at least one employee that contains the Name
:
var result = singleEntryReportCardModel
.Where(x => x
.EmployeeList
.Any(y => y.EmployeeName.Contains(Name)) //at least one employee contains the name
)
.ToList(); //obtain the list
Upvotes: 0
Reputation: 13381
variant for query syntax
var res = (from x in singleEntryReportCardModel
where x.EmployeeList.Any(y=>y.EmployeeName.Contains(Name))
select x).ToList();
Upvotes: 1