What would be Linq for Following
Following is the case for which I intend to write my LINQ query, but it does not work:
List <Clients>
has client info and in this list there is List<JobCards>
, which represents the list of job cards of that person. The job card list has one attribute named Status
. I need to return all the active job cards in all Clients List.
Can it be done in LINQ?
Other code may be as follows:
BindingList<JobCard> activeJobs = new List<JobCards>();
foreach(var client in allClientList)
{
foreach(var jobCard in client.JobCards)
{
if (jobCard.Status == "Active")
{
activeJobs.Add(jobCard);
}
}
}
I am in the learning phase of LINQ. I am certain there is some error in what I've 开发者_如何学Cimplemented, but I'm not sure how to fix it. Here is my LINQ query:
activeJobCards = new BindingList<JobCard>(
mainForm.allData.Where(
index => index.JobCards.Where(
card => card.Status == "active"
).ToList().Count > 0
).ToList()
);
What you are looking for is SelectMany
allClientList.SelectMany(c => c.JobCards).Where(jc => jc.Status == "Active");
SelectMany()
will give you an IEnumerable<JobCard>
and from there you select the Active job cards.
allClientList.SelectMany(c => c.JobCards.Where(jc => jc.Status == "Active"));
BindingList<JobCard> activeJobs = new List<JobCards>();
activeJobs.AddRange(allClientList.SelectMany( x=> x.JobCards)
.Where( y => y.Status == "Active"));
精彩评论