简体   繁体   中英

Converting object property values to dictionary

Lets say, I have a list of objects like this

public class Room{
    public string Name {get; set;}
    public int[] UserId {get; set;}
}

What could be an efficient way of converting this list to dictionary like the following

Dictionary<int, List<string>> 

where the key is the UserId and String is the name of the room. Thanks in Advance.

I would use Linq's Aggregate method as shown below. ( Note I took liberties with the original object to be a List vs an array for the demo, but you can change that ).

var names = new List<Room>()
{
    new Room() { Name = "Alpha", UserId = new List<int> { 10, 40 }},
    new Room() { Name = "Omega", UserId = new List<int> { 10, 20, 30 }},
};

// Aggregate needs an item to pass around, we will
// seed it with the dictionary which will be the ultimate returned
// value. The following lambda takes a dictionary object (`dict`)
// and the current room ('current') to add to the dictionary. 
names.Aggregate (new Dictionary<int, List<string>>(), (dict, current) =>
            {
               current.UserId.ForEach(id => {
                                               if (dict.ContainsKey(id) == false)
                                                  dict.Add(id, new List<string>());

                                               dict[id].Add(current.Name);
                                            });
                return dict;
            });

Result:

在此输入图像描述

Concept

  • Iterate through the List of Rooms.
  • If the dictionary contains the UserID add the name to the associated list.
  • Otherwise make a new dictionary item.

Implementation

foreach (Room r in RoomsList) {
    foreach (int id in r.UserID) {
        if (RoomDictionary.Contains(id))
            RoomDictionary[id].Add(r.Name);
        else
            RoomDicationary.Add(id, new List<string>() { r.Name });
    }
}

Or something like that I just typed that into the web browser so it may need some adjusting but something like that.

Just some clarification, since UserId is declared as an array from your class Room. Assuming it is not an array, and 1 id corresponds to 1 room name. A RoomCollection implementing IDictionary would give you better control as shown below:

 public class RoomCollection : IDictionary<int, string>
{
    private Dictionary<int, string> roomCollection = new Dictionary<int, string>();

    //Add modified version of Add()
    public void Add(Room room)
    {
        //Do something to efficiently check whether room already exists
        this.Add(room.UserId, room.Name);
    }

    public void Add(int key, string value)
    {
        //Checking can be done here
        if (this.roomCollection.ContainsKey(key))
        {
            this.roomCollection[key] = value; //Overwrite values
        }
        else
        {
            this.roomCollection.Add(key, value); //Create new item
        }
    }

    //Modify other functionalities to your own liking
    public bool ContainsKey(int key)
    {
        return this.roomCollection.ContainsKey(key);
    }

    public ICollection<int> Keys
    {
        get { throw new NotImplementedException(); }
    }

    public bool Remove(int key)
    {
        throw new NotImplementedException();
    }

    public bool TryGetValue(int key, out string value)
    {
        throw new NotImplementedException();
    }

    public ICollection<string> Values
    {
        get { throw new NotImplementedException(); }
    }

    public string this[int key]
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public void Add(KeyValuePair<int, string> item)
    {
        throw new NotImplementedException();
    }

    public void Clear()
    {
        throw new NotImplementedException();
    }

    public bool Contains(KeyValuePair<int, string> item)
    {
        throw new NotImplementedException();
    }

    public void CopyTo(KeyValuePair<int, string>[] array, int arrayIndex)
    {
        throw new NotImplementedException();
    }

    public int Count
    {
        get { throw new NotImplementedException(); }
    }

    public bool IsReadOnly
    {
        get { throw new NotImplementedException(); }
    }

    public bool Remove(KeyValuePair<int, string> item)
    {
        throw new NotImplementedException();
    }

    public IEnumerator<KeyValuePair<int, string>> GetEnumerator()
    {
        throw new NotImplementedException();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        throw new NotImplementedException();
    }
}

public class Room
{
    public string Name { get; set; }
    public int UserId { get; set; }
}

public class TestCollection
{
    public void Test()
    {
        Room r1 = new Room();
        r1.UserId = 1;
        r1.Name = "Room One";

        Room r2 = new Room();
        r2.UserId = 2;
        r2.Name = "Room Two";

        RoomCollection roomCollection = new RoomCollection();
        roomCollection.Add(r1);
        roomCollection.Add(r2);

        foreach (int roomId in roomCollection.Keys)
        {
            Console.WriteLine("Room number: {0} - Room name: {1}", roomId, roomCollection[roomId]);
        }
    }
}

This seems quite straight forward:

var rooms = new List<Room>()
{
    new Room() { Name = "Alpha", UserId = new List<int>() { 10, 40 }.ToArray() },
    new Room() { Name = "Omega", UserId = new List<int>() { 10, 20, 30 }.ToArray() },
};

var query =
    from r in rooms
    from u in r.UserId 
    group r.Name by u;

var result = query.ToDictionary(x => x.Key, x => x.ToList());

The result I get is:

结果

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