Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
920 views
in Technique[技术] by (71.8m points)

.net - Comparing two lists using linq to sql

Say I have two lists:

List<CanidateSkill> canidateSkills;
List<JobDesiredSkill> desiredSkills;

class CanidateSkill
{
    public Guid CanidateId { get; set; }
    public Guid SkillId { get; set; }
}

class JobDesiredSkill
{
    public Guid JobId { get; set; }
    public Guid SkillId { get; set; }
}

How do you determine if:

  1. At least one item in JobDesiredSkills is contained in CandidateSkills (matched on SkillId)

  2. All items in JobDesiredSkills are contained in CandidateSkills

I tried this, but get this error: Unable to create a constant value of type Only primitive types ('such as Int32, String, and Guid') are supported in this context.

 return from candidate in _db.Candidates                           
 where (candidate.CandidateSkills.Any(c => job.JobDesiredSkills.Any(j => j.SkillId == c.SkillId))) 
 select candidate;

I also tried this, but Contains expects a JobDesiredSkill object, but c is a CandidateSkillObject.

 return from candidate in _db.Candidates                           
 where CandidateSkills.Any(c => JobDesiredSkills.Contains(c)) 
 select candidate;

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There are two linq methods that fit your exact needs:

  1. IEnumerable.Any()
  2. IEnumerable.All()

Edit:

You need to select a "Projection" of the "Ids" in the collection to get an enumerable collection of them, then you can use any / all on those (you can't compare complex types without an explicit comparison object).

Here is a trivial example, I hope it helps.

List<Guid> skills = 
    new List<Guid>( Enumerable.Range( 0, 20 ).Select( n => Guid.NewGuid() ) );

List<CanidateSkill> canidateSkills = new List<CanidateSkill>
(
    Enumerable.Range( 0, 10 ).Select( c => new CanidateSkill() { CanidateId = Guid.NewGuid(), SkillId = skills.ElementAt( c ) } )
);

List<JobDesiredSkill> desiredSkills = new List<JobDesiredSkill>
(
    Enumerable.Range( 5, 15 ).Select( d => new JobDesiredSkill() { JobId = Guid.NewGuid(), SkillId = skills.ElementAt( d ) } )
);

var anyDesiredSkills = canidateSkills.Any( c => desiredSkills.Select( ds => ds.SkillId ).Contains( c.SkillId ) ); // true
var allDesiredSkills = canidateSkills.All( c => desiredSkills.Select( ds => ds.SkillId ).Contains( c.SkillId ) ); // false

(Note: I also edited your question to update the sample classes used in this code, hope you don't mind.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...