在两个IEnumerable之间搜索 - LINQ

时间:2012-11-07 11:50:54

标签: c# linq ienumerable

你能帮我解决这个问题,我已经尝试了几件事。 我需要在两个IEnumerables之间进行搜索,这里是代码。

IEnumerable<Project> Projects = new[] { new Project {id = "1", lan = "test1"},  new Project {id = "2", lan = "test1"}}

IEnumerable<string> lan = new [] { "test1", "test2"};
IEnumerable<string> indexFiltered = ?;

我需要做一个linq查询,返回在lan中有任何Project.lan的Project.id。

有什么想法吗?

5 个答案:

答案 0 :(得分:3)

我使用HashSet而不是数组,因为它允许check-if-contains作为O(1),而不是O(n),操作:

HashSet<string> lan = new HashSet<string> { "test1", "test2" };
IEnumerable<string> indexFiltered = projects
    .Where(p => lan.Contains(p.lan))
    .Select(p => p.id);

答案 1 :(得分:2)

怎么样

indexFiltered = Projects.Where(p=>lan.Any(l=>l==p.lan)).Select(p=>p.Id); 

答案 2 :(得分:2)

 var results = projects.Where(p => lan.Contains(p.lan));

答案 3 :(得分:0)

另一种有效的方法是使用Enumerable.Join,因为它是作为哈希表实现的:

IEnumerable<string> indexFiltered = from p in Projects
                                    join l in lan on p.lan equals l
                                    select p.id;

Why is LINQ JOIN so much faster than linking with WHERE?

Join运算符从第一个表中获取行,然后仅获取第二个表中具有匹配键的行,然后仅获取第三个表中具有匹配键的行。

答案 4 :(得分:0)

我会使用IEnumerable.Join()。在内部,它使用HashSet来区分:

var Projects = new[] { new {id = "1", lan = "test1"},  new {id = "2", lan = "test1"}};
var lan = new [] { "test1", "test2"};

var results = Projects.Join(lan,
                              project => project.lan,
                              lanName => lanName,
                              (project, lanName) => project.id);

foreach (var result in results)
{
    Console.WriteLine("ID found: ", result);
}