开发者

Linq Count Expression

Suppose the following Employee class (yes I know I shouldn't publicly expose Lists but this is just an example):

class Employee
{
    public string Name {get; set;}
    public List<string> Skills {get; set;}
}

Skills is just a list of skills the employee has, for example "programming", "customer service", etc.

Now suppose I have a List<Employee> CurrentEmployees, and I also have another employee, Employee NewHire that is not in the CurrentEmployees list.

My goal is to use a lambda expression to count how many employees in CurrentEmployees have at least one skill that NewHire also has. So for example, if CurrentE开发者_Go百科mployees contains one employee with Skills{'Programming', 'Troubleshooting'}, and another employee with Skills{'Accounting','Finance'}, and NewHire has Skills{'Programming','Networking'}, I would want an expression that returns 1, because the first employee in the list also has 'Programming' as a skill... is this possible?

Thanks for any help.


 currentEmployees.Count(ce =>
               ce.Skills.Intersect(newHire.Skills).Any())


var currentEmployees = new List<Employee>
{
    new Employee { Skills = new List<string> { "Programming", "Troubleshooting" } },
    new Employee { Skills = new List<string> { "Accounting", "Finance" } },
};

var newHire = new Employee { Skills = new List<string> { "Programming", "Networking" } };

var count = currentEmployees.Count(e => e.Skills.Any(newHire.Skills.Contains));
// count == 1


If performance was important, I would use a HashSet<string>:

var newHireSkills = new HashSet<string>(newHire.Skills);

var count = currentEmployees.Count(e => e.Skills.Any(s => newHireSkills.Contains(s)));
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜