Click here to Skip to main content
15,894,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello all,

I have a IEnumerable<Principle> say users which contains 100 items. And I have IEnumerable>DataRow> say groupUsers which contains 10 items.

"Principle" contains fields of id, name, surname, emailaddress
"Datarow" contains fields of company, name, surname, email

I want to loop on users and for each item on users.mailaddress equals to groupUsers.Email I want to add the users's item to a IEnumerable<principle>. Can someone help me write the LINQ statement.


What I have came up so far;

C#
IEnumerable<Principle> result = users.ForEach(x => x.Emailaddress.Select(//another loop here for matching emails));


Thanks in advance.
Posted
Updated 16-Jul-14 5:23am
v2

1 solution

Look at it from the inner test first:
A Principle should be included in the output if the Emailaddress matches any of the Email values in groupUsers:
C#
groupUsers.Any(gu => gu.Email == u.Emailaddress)

Now do that for each element of users and collect the result:
C#
IEnumerable<Principle> result = users.Where(u => groupUsers.Any(gu => gu.Email == u.Emailaddress));

This, of course, is very inefficient. Time grows proportional to the product of the lengths of the two lists. So make the inner test faster:
C#
HashSet<string> groupEmails = new HashSet<string>(groupUsers.Select(gu => gu.Email));
IEnumerable<Principle> result = users.Where(u => groupEmails.Contains(u.Emailaddress));

This now takes time proportional to the sum of the lengths of the two lists.
Creating and populating the groupEmails is a single pass over the groupUsers collection.
Finding the result is a single pass over the users collection.
The advantage is that the groupEmails.Contains(...) is (approximately) constant time, independent of the number of elements in the groupEmails HashSet.

* Gramatically, you probably mean "Principal" not "Principle"... lookup the difference: Principal vs Principle[^]
 
Share this answer
 
Comments
wonder-FOOL 17-Jul-14 5:06am    
Hello Matt,

I really appreciate your help. Thank you very much for the descriptive solution you gave. It is the solution that I needed.

Also you are right about "Principal". I typed it wrong since English is not my native language.

Have a great day.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900