开发者

How do I simplify a LINQ query with multiple .Select() in order to return an IQueryable(int)

In the LINQ query below, I want to return the ContractorId found in the Contractors table. Not all people in the Contacts table are in the Contractors table. What I really want is a list of ContractorIds for those contractors meeting the criteria. ContractorId is not the same as ContactId.

var contractorsWithCertsFor2010 = dc.Contacts.Where(x => x.Contractors
.Any(d => d.ContractorStatus
.Any(date => date.StatusDate.Year >= 2010)))
.Select(x => x.Contractors
.Select(dr => dr.ContractorId)); 

IEnumerable<int> diff开发者_运维知识库erenceQuery = allPeople.Except(contractorsWithCertsFor2010);

allPeople is a IQueryable<Int> but contractorsWithCertsFor2010 is a IQueryable<IEnumerable<Int>>. Something isn't right there. The multiple .Select() is causing the IQueryable<IEnumerable<Int>> so I'm looking for a way to eliminate one of the .Select() and get a return of

IQueryable<Int>

Any Suggestions? Thanks!

Solution: One solution is posted in a reply below. I created another solution prior to seeing that one. In my solution, I started out in the Contractors table instead of the Contacts table, eliminating one layer and one .Select() statement.


Assuming you only want contractors that have contact record and since the only thing you selecting is the contractor id, you might want to try this:

var contractorsWithCertsFor2010 = dc.Contractors
    .Where(c => c.Contacts.Any() && c.ContractorStatus
        .Any(cs => cs.StatusDate.Year >= 2010))
    .Select(c => c.ContractorId);


First thought: Try SelectMany to flatten your results. So, identical code except for:

//...
.SelectMany(x => x.Contractors
                  .Select(dr => dr.ContractorId)); 

IEnumerable<int> differenceQuery = allPeople.Except(contractorsWithCertsFor2010);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜