本文介绍了比较使用LINQ to SQL两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个列表:

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. 在JobDesiredSkills

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

  1. 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:

  1. IEnumerable.Any()
  2. IEnumerable.All()
  1. IEnumerable.Any()
  2. 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.)

这篇关于比较使用LINQ to SQL两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 11:25