简体   繁体   English

从Collection中选择项目的优化方式,不包括使用Linq的某个成员的列表

[英]Optimized way to select items from a Collection excluding a list of certain member using Linq

I will explain it with an example. 我将用一个例子来解释它。

Suppose I have a List of Student Object, Where Student Class is, 假设我有一个学生对象列表,学生班级在哪里,

class Student
{
    public int RollNo {get; set;}
    public string Name { get; set; }
    public int StateId { get; set; }
}

and a List containing special StateIds 和一个包含特殊StateIds的List

List<int> specialStateIds;

Now I want to extract List of RollIds from Students List which doesn't belong to specialStates. 现在我想从学生列表中提取不属于specialStates的RollIds列表。 Currently I'm doing it as following. 目前我正在做如下。

List<int> NonSpacialRollIds = Students.Where(s => 
      !specialStateIds.Contains(s.StateId)).Select(s => s.RoleIds).ToList();

But somehow I feel, It can be optimize further using Linq and Contains extension method of Collections can be avoided. 但不知怎的,我觉得,可以使用Linq进一步优化,并且可以避免包含集合的扩展方法。

You can create set of state ids for faster search, because Contains() operation on hash set is O(1) and Contains on list is O(N): 您可以创建一组状态ID以加快搜索速度,因为哈希集上的Contains()操作是O(1),列表中的Contains是O(N):

HashSet<int> ids = new HashSet<int>(specialStateIds);

List<int> NonSpacialRollIds = Students.Where(s => !ids.Contains(s.StateId))
                                      .Select(s => s.RoleIds)
                                      .ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM