user9393635
user9393635

Reputation: 1429

What would be the most appropriate collection to use for this scenario?

What would be the most appropriate collection to use for this scenario, based on the latest version of .NET/C#? I need to return a mapping of group id's with user id's. So consider a mapping like the example below where group 111 has 2 users 222 and 444:

111 222
111 444
555 222

A KeyValuePair would not be the most efficient b/c the data reflects a many-to-many relationship.

Upvotes: 0

Views: 172

Answers (3)

oliver
oliver

Reputation: 2901

If all you want to find out is the users in a group and whether a specific user is in a given group most efficiently (i.e. for probably thousands of users), but you don't need to be that efficient in determining what groups a single user is in, you might also consider using

Dictionary<int, HashSet<int>> users = new Dictionary<int, HashSet<int>>();

// Adding a new group:
users[newGroup] = new HashSet<int>();

// Adding a new user to the group:
users[newGroup].Add(newUser);

// Then to find all users in a group:
HashSet<int> usersInAGroup = users[aGroup];

// If you want to know very fast if a specific user is in this group, then:
if (usersInAGroup.Contains(aUser)) {/* yes, the given user is in this group */};

HashSet is particularly optimized for the Contains() operation on a lot of elements.

Upvotes: 0

NetMage
NetMage

Reputation: 26936

It is unfortunate that the LookUp class isn't fully public, but you can use Linq to create it:

public class GroupUserid {
    public int group;
    public int userid;
}

var rawdata = List<GroupUserid>();
var groupMembership = rawdata.ToLookup(d => d.group, d => d.userid);

Then you can lookup the members of a group with:

var membersIn111 = groupMembership[111];

Upvotes: 0

Eric Lippert
Eric Lippert

Reputation: 660513

The data structure you want is called "multimap", "multidictionary", or "multivaluedictionary" depending on who you ask.

There are lots of implementations of such; do a web search and you'll find some. For example:

https://blogs.msdn.microsoft.com/dotnet/2014/08/05/multidictionary-becomes-multivaluedictionary/

https://www.dotnetperls.com/multimap

and so on.

Upvotes: 3

Related Questions