LINQ通过循环另一个列表来过滤列表 [英] LINQ Filtering a list by looping on another list
问题描述
大家好,
我有 IEnumerable< Principle>
说用户其中包含100个项目。我有 IEnumerable> DataRow>
说 groupUsers ,其中包含10个项目。
原则包含身份证,姓名,姓氏,电子邮件地址
Datarow包含公司,姓名,姓氏,电子邮件等字段/>
我想循环用户和users.mailaddress上的每个项目等于groupUsers.Email我想添加用户的项目为IEnumerable< principle>。有人可以帮我写LINQ声明吗。
到目前为止我得到了什么;
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;
IEnumerable<Principle> result = users.ForEach(x => x.Emailaddress.Select(//another loop here for matching emails));
提前谢谢。
Thanks in advance.
推荐答案
首先从内部测试中查看它:
A原则
应该包含在如果Emailaddress
与groupUsers中的电子邮件
值的任何匹配,则输出:
Look at it from the inner test first:
APrinciple
should be included in the output if theEmailaddress
matches any of the
groupUsers.Any(gu => gu.Email == u.Emailaddress)
现在为每个用户元素执行此操作并收集结果:
Now do that for each element of users and collect the result:
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:
HashSet<string> groupEmails = new HashSet<string>(groupUsers.Select(gu => gu.Email));
IEnumerable<Principle> result = users.Where(u => groupEmails.Contains(u.Emailaddress));
现在需要时间与两个列表的长度的总和成比例。
创建和填充 groupEmails
是一个单次传递 groupUsers
集合。
查找结果是单次传递用户
集合。
优点是 groupEmails.Contains(...)
是(近似)恒定时间,与元素数量无关在 groupEmails HashSet
。
*从字面上看,你可能意味着校长不是原则......查找差异:委托人与原则 [ ^ ]
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[^]
这篇关于LINQ通过循环另一个列表来过滤列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!