[英]How to retrieve a list of distinct values from a list within a list
I have a list of objects and in each object they contain a list of ids. 我有一个对象列表,并且在每个对象中它们都包含一个ID列表。
The code below creates a list of 10 members and then creates a list of five random ids in each member. 下面的代码创建一个包含10个成员的列表,然后在每个成员中创建一个包含五个随机ID的列表。
public class Member
{
List<int> Ids { get; set; }
public Member()
{
Ids = new List<int>();
}
}
var rnd = new Random();
var container = new List<Member>();
// Add members with random Ids
for ( int i = 1; i <= 10; i++ ){
var member = new Member();
for ( int j = 1; j <= 5; j++ ){
member.Ids.Add( rnd.Next(100) );
}
}
var distinctIds = ?????;
What I'm struggling with is the LINQ to retrieve a distinct list of the Ids for all members. 我正在努力的是LINQ,以检索所有成员的ID的唯一列表。
var distinctIds =
(from member in container
from id in member.Ids
select id).Distinct();
There is of course the method-y syntax, which in this case would be using SelectMany
: 当然有method-y语法,在这种情况下将使用
SelectMany
:
var distinctIds = container.SelectMany(member => member.Ids).Distinct();
but I can never remember how to call it, so I generally prefer multiple from
s. 但我永远记得怎么称呼它,所以我一般喜欢多
from
秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.