cullimorer
cullimorer

Reputation: 755

LINQ - flatten list of objects with child list into one list

I have a class called Activity and this class has a child list of Users. Here is what it looks like:

public class Activity
{
    public Activity()
    {
    }

    public string Number { get; set; }
    public virtual ICollection<User> Users { get; set; }        
}

The user class looks like:

public class User
{
    public User()
    {
    }

    public string Name { get; set; }        
}

Using LINQ, I would like to build a "List<KeyValuePair<string,User>>()". So for example, if I had a data set that looked like this:

var activities = new List<Activity>()
{
    new Activity()
    {
        Number = "ActivityA",
        Users = new List<User>()
        {
            new User()
            {
                Name = "UserA"
            },
            new User()
            {
                Name = "UserB"
            },
            new User()
            {
                Name = "UserC"
            }
        }
    },
    new Activity()
    {
        Number = "ActivityB",
        Users = new List<User>()
        {
            new User()
            {
                Name = "UserD"
            },
            new User()
            {
                Name = "UserE"
            },
            new User()
            {
                Name = "UserF"
            }
        }
    }
};

What LINQ statement would I need to write in order for my output KeyValuePair list to look like this:

enter image description here

Upvotes: 0

Views: 585

Answers (2)

Mohammed Sajid
Mohammed Sajid

Reputation: 4903

You can use SelectManay to flatten list of list of KeyValuePair<string, string> to one list, like the following code :

List<KeyValuePair<string, string>> keyValuePairs = activities
    .SelectMany(x => x.Users.Select(y => new KeyValuePair<string, string>(x.Number, y.Name)))
    .ToList();

If you want list of KeyValuePair<string, User>, use the following code:

List<KeyValuePair<string, User>> keyValuePairs = activities
    .SelectMany(x => x.Users.Select(y => new KeyValuePair<string, User>(x.Number, y)))
    .ToList();

Note that, Number of activities considered unique.

Number and Name must be a string.

i hope this will help you out.

Upvotes: 1

Sathish Guru V
Sathish Guru V

Reputation: 1479

Use a LINQ Select and SelectMany to transform the objects to new form.

Edited as per the OP's modification.

var results = activities.SelectMany(activity => activity.Users.Select(user => new KeyValuePair<string, string>(activity.Number, user.Name))).ToList();

Though the Class have the Name and Number as int but the Data is defined as strings.

Upvotes: 0

Related Questions