简体   繁体   中英

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.

The code below creates a list of 10 members and then creates a list of five random ids in each member.

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.

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 :

var distinctIds = container.SelectMany(member => member.Ids).Distinct();

but I can never remember how to call it, so I generally prefer multiple from s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM