比较使用LINQ to SQL两个列表两个、列表、LINQ、to

2023-09-03 01:38:35 作者:莪掵甴Wǒ不甴天

说我有两个列表:

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:

在JobDesiredSkills

至少有一个项目包含在CandidateSkills(匹配上SkillId)

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

在JobDesiredSkills所有项目都包含在CandidateSkills

All items in JobDesiredSkills are contained in CandidateSkills

我想这一点,但得到这个错误:无法创建类型只有原始类型的恒定值(如的Int32,字符串和GUID')在这方面的支持。

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;

我也试过这个,但包含需要一个JobDesiredSkill对象,但c是一个CandidateSkillObject。

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;

感谢

推荐答案

有适合​​您的具体时有两个LINQ方法:

There are two linq methods that fit your exact needs:

IEnumerable.Any() IEnumerable.All() IEnumerable.Any() IEnumerable.All()

编辑:

您需要集合中选择标识的投影,让他们的枚举集合,那么你可以使用任何/所有这些(没有一个明确的比较对象,你不能比较复杂类型)

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

(注意:我还编辑您的问题更新此code中使用的示例类,希望你不要介意)

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