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。
有什么想法吗?
答案 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);
}