3

Hi can you guys help me with this, I have try several things. I need to search between two IEnumerables, here is the code.

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 = ?;

I need to do a linq query that return the Project.id thats have any Project.lan in lan.

Any idea?

Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
Don Juan
  • 171
  • 2
  • 17

5 Answers5

3

I'd use a HashSet rather than an array, as it allows check-if-contains as an O(1), rather than O(n), operation:

HashSet<string> lan = new HashSet<string> { "test1", "test2" };
IEnumerable<string> indexFiltered = projects
    .Where(p => lan.Contains(p.lan))
    .Select(p => p.id);
Rawling
  • 49,248
  • 7
  • 89
  • 127
2

How about

indexFiltered = Projects.Where(p=>lan.Any(l=>l==p.lan)).Select(p=>p.Id); 
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
2
 var results = projects.Where(p => lan.Contains(p.lan));
Mahmoud Gamal
  • 78,257
  • 17
  • 139
  • 164
0

Another efficient approach is using Enumerable.Join since it's implemented as a hash table:

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?

The Join operator takes the rows from the first tables, then takes only the rows with a matching key from the second table, then only the rows with a matching key from the third table.

Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

I would use IEnumerable.Join(). Internally it uses the HashSet to do the distinction:

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);
}
Oliver
  • 43,366
  • 8
  • 94
  • 151